`

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
分享到:
评论
发表评论

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

相关推荐

    Add Textbox Dynamically using jQuery.zip

    "Add Textbox Dynamically using jQuery.zip"这个压缩包中的示例,主要展示了如何利用jQuery在用户交互时动态创建一个新的文本输入框。 首先,jQuery库是一个强大的JavaScript库,它简化了DOM操作、事件处理、动画...

    JQuery In Action.PDF

    - **Using JQuery with Other Libraries:** JQuery is designed to play well with other JavaScript libraries and frameworks. By using the `.noConflict()` method, developers can integrate JQuery ...

    Scrolling Dynamically Loaded Text (as2)

    标题 "Scrolling Dynamically Loaded Text (as2)" 涉及的是在ActionScript 2(AS2)中创建滚动的动态加载文本的技术。这通常用于Web开发中的Flash内容,允许文本内容随着用户滚动而动态加载,提高网页性能,因为不是...

    Practical jQuery(Apress,2015)

    Using this book, you will learn how to use jQuery's powerful DOM manipulation tools to dynamically update content on your site. You will be able to extend jQuery's capabilities by writing your own ...

    Manning jQuery in Action.pdf

    - **Using jQuery with Other Libraries**: jQuery integrates seamlessly with other JavaScript libraries, making it possible to combine the strengths of multiple tools. **4. Selecting Elements for ...

    Beginning.jQuery

    Animate content and build your own image slider with jQuery’s animation tools Extend the library by writing your own custom plug ins Avoid common beginner errors and learn how to use best practices...

    jquery图片切换

    jquery图片切换 Features Slides are HTML Content (can be anything) Next Slide / Previous Slide Arrows Navigation tabs are built and added dynamically (any number of slides) Optional custom function for...

    jquery mobile web api 带下拉,上拉滑动分页滚动示例

    // Append new data to the listview and enhance it with jQuery Mobile $.each(data, function () { $("&lt;li&gt;&lt;/li&gt;").text(this.title).appendTo("#your-listview"); }); $("#your-listview").listview(...

    Beginning JavaScript with DOM Scripting and Ajax: Second Editon

    Dynamically manipulate markup, validate forms and deal with images Debug applications using features inside the browser JavaScript is one of the most important technologies on the web. It provides the...

    Beginning JavaScript with DOM Scripting and Ajax (pdf + ePub)

    Dynamically manipulate markup, validate forms and deal with images Debug applications using features inside the browser JavaScript is one of the most important technologies on the web. It provides ...

    Raspberry.Pi.Home.Automation.with.Arduino.2nd.Edition.178439

    Learn how to dynamically adjust your living environment with detailed step-by-step examples Who This Book Is For If you are new to the Raspberry Pi, the Arduino, or home automation and wish to develop...

    jqgrid API 3.6.5

    Since the grid is a client-side solution loading data dynamically through Ajax callbacks, it can be integrated with any server-side technology, including PHP, ASP, Java Servlets, JSP, ColdFusion, and...

    Jquery JS Color

    Jquery Color for your web browser by which any one can change the website color dynamically.

Global site tag (gtag.js) - Google Analytics