`

Dynamically shortened Text with “Show More” link using jQuery

阅读更多

文章源自:http://viralpatel.net/blogs/dynamically-shortened-text-show-more-link-jquery/

Dynamically shortened Text with “Show More” link using jQuery

Update: The plugin is now on GitHub: https://github.com/viralpatel/jquery.shorten

Facebook user updates has a great functionality. If the comment text is larger than few characters, the extra words are hide and a show more link is presented to user. This way you can keep long text out of the view to user and stop the cluttering of page. Also interested users can click on more link and see the full content.

Here is a simple tutorial to achieve this using jQuery / Javascript.

The HTML

Below is the sample text. Each text is wrapped in a DIV tag. Note that we have added a class “more” in each div. This class will decide if a text needs to be shortened and show more link showed or not.

<div class="comment more">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    Vestibulum laoreet, nunc eget laoreet sagittis,
    quam ligula sodales orci, congue imperdiet eros tortor ac lectus.
    Duis eget nisl orci. Aliquam mattis purus non mauris
    blandit id luctus felis convallis.
    Integer varius egestas vestibulum.
    Nullam a dolor arcu, ac tempor elit. Donec.
</div>
<div class="comment more">
    Duis nisl nibh, egestas at fermentum at, viverra et purus.
    Maecenas lobortis odio id sapien facilisis elementum.
    Curabitur et magna justo, et gravida augue.
    Sed tristique pellentesque arcu quis tempor.
</div>
<div class="comment more">
    consectetur adipiscing elit. Proin blandit nunc sed sem dictum id feugiat quam blandit.
    Donec nec sem sed arcu interdum commodo ac ac diam. Donec consequat semper rutrum.
    Vestibulum et mauris elit. Vestibulum mauris lacus, ultricies.
</div>

The CSS

Below is the CSS code for our example. Note the class “.morecontent span” is hidden. The extra text from the content is wrapped in this span and is hidden at time of page loading.

a {
    color: #0254EB
}
a:visited {
    color: #0254EB
}
a.morelink {
    text-decoration:none;
    outline: none;
}
.morecontent span {
    display: none;
}
.comment {
    width: 400px;
    background-color: #f0f0f0;
    margin: 10px;
}

 

The Javascript

Below is the Javascript code which iterate through each DIV tags with class “more” and split the text in two. First half is showed to user and second is made hidden with a link “more..”.

You can change the behaviour by changing following js variables.

  • showChar: Total characters to show to user. If the content is more then showChar, it will be split into two halves and first one will be showed to user.
  • ellipsestext: The text displayed before “more” link. Default is “…”
  • moretext: The text shown in more link. Default is “more”. You can change to “>>”
  • lesstext: The text shown in less link. Default is “less”. You can change to “<<"
$(document).ready(function() {
    var showChar = 100;
    var ellipsestext = "...";
    var moretext = "more";
    var lesstext = "less";
    $('.more').each(function() {
        var content = $(this).html();
 
        if(content.length > showChar) {
 
            var c = content.substr(0, showChar);
            var h = content.substr(showChar-1, content.length - showChar);
 
            var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';
 
            $(this).html(html);
        }
 
    });
 
    $(".morelink").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });
});

 

Update

The above code is modified into jQuery plugin. Also it has now been enhanced. HTML tags are now parsed properly within text to preserve its uniformity while shorting the text. Please check latest plugin code on GitHub. https://github.com/viralpatel/jquery.shorten


jQuery Plugin

Code

/*
 * jQuery Shorten plugin 1.0.0
 *
 * Copyright (c) 2013 Viral Patel
 * http://viralpatel.net
 *
 * Dual licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 */
 
 (function($) {
    $.fn.shorten = function (settings) {
     
        var config = {
            showChars: 100,
            ellipsesText: "...",
            moreText: "more",
            lessText: "less"
        };
 
        if (settings) {
            $.extend(config, settings);
        }
         
        $(document).off("click", '.morelink');
         
        $(document).on({click: function () {
 
                var $this = $(this);
                if ($this.hasClass('less')) {
                    $this.removeClass('less');
                    $this.html(config.moreText);
                } else {
                    $this.addClass('less');
                    $this.html(config.lessText);
                }
                $this.parent().prev().toggle();
                $this.prev().toggle();
                return false;
            }
        }, '.morelink');
 
        return this.each(function () {
            var $this = $(this);
            if($this.hasClass("shortened")) return;
             
            $this.addClass("shortened");
            var content = $this.html();
            if (content.length > config.showChars) {
                var c = content.substr(0, config.showChars);
                var h = content.substr(config.showChars, content.length - config.showChars);
                var html = c + '<span class="moreellipses">' + config.ellipsesText + ' </span><span class="morecontent"><span>' + h + '</span> <a href="#" class="morelink">' + config.moreText + '</a></span>';
                $this.html(html);
                $(".morecontent span").hide();
            }
        });
         
    };
 
 })(jQuery);

 

Usage

Step 1: Include the jQuery plugin in your HTML

<script type="text/javascript"
    src="http://viralpatel.net/blogs/demo/jquery/jquery.shorten.1.0.js"></script>

 Step 2: Add the code to shorten any DIV content. In below example we are shortening DIV with class “comment”.

<div class="comment">
    This is a long comment text.
    This is a long comment text.
    This is a long comment text.
    This is a long comment text. This is a long comment text.
</div>
<script type="text/javascript">
    $(document).ready(function() {
     
        $(".comment").shorten();
     
    });
</script>

 You may want to pass the parameters to shorten() method and override the default ones.

$(".comment").shorten({
    "showChars" : 200
});
 
 
$(".comment").shorten({
    "showChars" : 150,
    "moreText"  : "See More",
});
 
$(".comment").shorten({
    "showChars" : 50,
    "moreText"  : "See More",
    "lessText"  : "Less",
});

 

 

  • 大小: 1.7 KB
分享到:
评论
发表评论

文章已被作者锁定,不允许评论。

相关推荐

    hi-z测试文件遮挡剔除

    hi-z测试文件遮挡剔除

    毕业设计-喝酒-整站商业源码.zip

    毕业设计-喝酒-整站商业源码.zip

    生成对抗网络在计算机视觉领域的应用.pdf

    生成对抗网络在计算机视觉领域的应用.pdf

    光学仿真领域COMSOL远场偏振通用计算方法及Matlab辅助分析

    内容概要:本文详细介绍了COMSOL在远场偏振通用计算中的应用,涵盖从建模到仿真的完整流程。首先解释了远场偏振的概念及其在光学模拟中的重要性,接着逐步讲解了如何在COMSOL中建立光学模型、划分网格、设置参数并运行仿真。随后,重点讨论了如何解读远场偏振图和能带结构图,最后介绍了如何使用Matlab程序读取COMSOL输出数据并进行进一步的分析和绘图。通过这些步骤,读者可以全面掌握COMSOL在远场偏振计算中的应用。 适合人群:从事光学仿真领域的研究人员和技术人员,尤其是那些希望深入了解COMSOL软件及其与Matlab集成使用的专业人士。 使用场景及目标:适用于需要进行复杂光学仿真和数据分析的研究项目,旨在提高对光波传播行为和材料特性的理解,促进相关领域的科研创新。 阅读建议:建议读者跟随文中提供的具体步骤进行实际操作练习,同时结合Matlab代码示例加深理解。对于初学者来说,可以从简单模型入手,逐渐过渡到更复杂的仿真任务。

    07-组成原理1.3选择6-10.sz

    07-组成原理1.3选择6-10.sz

    SecureCRT-Portable安装包

    SecureCRT-Portable安装包

    机器人导航中改进DWA算法的地图动态优化与路径规划 自适应动态窗口 改进DWA算法:支持地图换图与自我输入栅格地图的优化路径规划方法

    内容概要:本文详细介绍了对传统DWA(Dynamic Window Approach)算法的改进,旨在解决机器人在复杂环境中遇到的问题。主要改进点包括:地图动态优化,允许通过图片形式加载并随时更换地图;引入自适应动态窗口策略,帮助机器人逃出C型障碍物等复杂地形的局部最优解;以及轨迹优化,使机器人的移动轨迹更优、更光滑、速度更快。实验结果显示,改进后的DWA算法在实际应用中表现出色,提高了机器人应对复杂环境的能力。 适合人群:从事机器人研究、开发及相关领域的科研人员和技术爱好者。 使用场景及目标:适用于需要在复杂环境中进行高效、安全导航的机器人系统,如无人驾驶车辆、自动导引车(AGV)等。目标是提升机器人在未知或变化环境中自主导航的能力。 其他说明:本文不仅提供了理论分析,还展示了具体的实现方法和效果对比,有助于读者深入理解改进措施及其带来的性能提升。

    钉钉消息加密及批量推送系统1.0上线

    钉钉消息加密及批量推送系统1.0上线

    液滴偏心碰撞的多体耗散粒子动力学研究.pdf

    液滴偏心碰撞的多体耗散粒子动力学研究.pdf

    MATLAB环境下的一维时间序列信号同步压缩小波包变换算法及其应用 MATLAB

    内容概要:本文详细介绍了在MATLAB R2018A环境中实现的一维时间序列信号同步压缩小波包变换算法。该算法通过引入同步压缩技术,显著提升了对信号瞬时成分的检测能力。文中不仅阐述了算法的基本原理和执行步骤,还展示了其在模拟信号和实际信号(如金融时间序列、地震信号、语音信号、声信号、生理信号等)中的具体应用实例。此外,文章讨论了算法的应用范围和迁移潜力,强调了其在多个领域的广泛应用前景。 适合人群:从事信号处理、数据分析及相关领域的研究人员和技术人员,尤其是那些熟悉MATLAB并希望深入了解小波包变换技术的人群。 使用场景及目标:适用于需要对一维时间序列信号进行高精度时频分析的研究项目。主要目标是提高对信号瞬时成分的检测能力和提取有用的特征信息,从而为后续的数据处理和分析提供坚实的基础。 其他说明:该算法不仅可以应用于现有的MATLAB环境,还可以迁移到其他类似平台,进一步扩展其应用场景。同时,文中提供的代码示例和参数设置指南有助于读者快速上手并深入理解算法的工作机制。

    基于dq坐标系的构网变流器功率控制技术:下垂控制与电压前馈响应的应用 电力电子

    内容概要:本文详细介绍了构网变流器在dq坐标系下的功率控制技术,重点探讨了下垂控制、无功下垂比例积分控制以及电压电流双闭环和电压前馈技术。通过这些技术手段,可以实现功率的准确、快速无静差跟踪和电压的高精度跟踪。文中还展示了具体的控制算法和伪代码示例,解释了如何利用PID和PI控制器调整系统参数,确保电力系统的稳定性和高效运行。 适合人群:从事电力电子系统研究与开发的技术人员,尤其是关注构网变流器功率控制领域的工程师和研究人员。 使用场景及目标:适用于需要优化电力系统性能的实际工程应用场景,旨在提高电力传输的稳定性、可靠性和效率。目标是帮助技术人员理解和掌握先进的功率控制技术,提升系统设计能力。 其他说明:随着电力电子技术的发展,新的控制策略和算法不断涌现,未来的研究将继续探索更高性能的解决方案,以应对更加复杂的电力系统需求。

    MAX31865.PDF

    MAX31865.PDF

    程序员2023年5月模拟试题1_1-10.pdf

    软考初级程序员相关文档

    langgenius-gpustack_0.0.7-offline.difypkg

    dify离线插件

    毕业设计-封装免签版苹果APP-整站商业源码.zip

    毕业设计-封装免签版苹果APP-整站商业源码.zip

    Python 安装使用全解析:下载配置、入门实操与算法应用指南

    打造 Python 安装使用教程,涵盖下载安装、入门操作及基础算法应用,详解环境搭建与实操技巧,助你快速掌握 Python,无论是编程新手还是想强化技能者,都能借此轻松提升,开启高效编程之旅。

    毕业设计-活动报名4.2.6+年卡1.1.7 全开源-整站商业源码.zip

    毕业设计-活动报名4.2.6+年卡1.1.7 全开源-整站商业源码.zip

    毕业设计-美容美发营销版小程序V2.0.1前后端完整源码-整站商业源码.zip

    毕业设计-美容美发营销版小程序V2.0.1前后端完整源码-整站商业源码.zip

    基于西门子S7-1200 PLC的饮料罐装生产线自动化控制流程详解与实战技巧 自动化控制

    内容概要:本文详细介绍了基于西门子S7-1200 PLC的饮料罐装生产线自动化控制系统的设计与实现。文章首先概述了罐装和贴标的主流程,通过梯形图程序展示了关键步骤,如罐装等待、压紧等待和贴标等待的具体逻辑。接着,重点讨论了实际调试过程中遇到的问题及其解决方案,如调整灌装时间和贴标机的安全区控制。此外,还提到了人机交互界面(HMI)的设计,特别是针对操作工人反馈进行优化的部分。最后,文中分享了一些实用的编程技巧,如急停触发后的批量复位、边沿检测以及产量统计。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是对PLC编程有一定基础并希望深入了解饮料罐装生产线自动化控制的人群。 使用场景及目标:适用于需要理解和实施饮料罐装生产线自动化控制的企业和个人。目标是提高生产线的稳定性和效率,同时掌握PLC编程的实际应用技巧。 其他说明:文章不仅提供了理论知识,还包括了许多来自现场调试的经验教训,有助于读者更好地应对实际工程中的挑战。

Global site tag (gtag.js) - Google Analytics