Last Updated: September 09, 2019
·
6.966K
· hslzr

"View more" button in html

Is pretty simple. Basically the same thing we see on Facebook, or other sites. All of this using jQuery.

$(document).ready(function() {
    var max_length = 150; //Your taste.
    var div = $('#that_one_div_selector_is_way_too_long');

    div.each( function(event) {   //Expands selection
        if( $(this).html().length > max_length ) {

            // Selects text up to your limit
            var short_text = $(this).html().substr(0, max_length);

            // Selec text from your limit to the end.
            var long_text = $(this).html().substr(max_length);

            // Modified html inside of your div.
            $(this).html(short_text + "...<a href='#' class='view_more'>View more...</a>" + "<span class='rest_of_text' style='display: none;'>" + long_text + "</span>");

            //Finds the a.read_more and binds it with the click function
            $(this).find('a.view_more').click(function(event) {

                //Prevents the 'a' from changing the url
                event.preventDefault();
                //Hides the 'view more' button/link 
                $(this).hide(); 
                //Displays the rest of the text.
                $(this).parents(div).find('.rest_of_text').show();
            )};
        }
    )}; 
)};

2 Responses
Add your response

can you make an example for ajax ?

over 1 year ago ·

Hi, @invalidtruck. I'll gladly update this tip. However, although this account is mine, I lost every possible access to it, so I made another one which is... this. I'll apreciate if you could forward your comments and thoughts to this one.

over 1 year ago ·