Show the 'View more' button using jQuery
This tiny codelines allow to display the 'View more' button in your wall texts, so it doesn't look gigantic or I don't know. Whatever you may use it.
$(document).ready(function() {
var my_div = $('.that_div_whose_selector_is_too_long');
/* Expands the selection to every item with that class */
my_div.each(function(event) {
var max_length = 150;
/* Verify if it surpasses the limit */
if (my_div.html().length > max_length) {
/* Cuts the text with the substr method. I'll explain it below */
var short_text = $(this).html().substr(0, max_length);
var long_text = $(this).html().substr(max_length);
/* Modifies the html so it displays the shortened text */
$(this).html(short_text +
"<a href='#' class='view_more_button'>...View more</a>" +
"<span class='rest_of_text' style='display: none;'>" + long_text + "</span>");
/* Note how we added a span containing the rest of the text, but it is not showing itself. */
$(this).find('a.view_more_button').click(function(event) {
/* Prevents the 'a' from changing the url */
event.preventDefault();
/* Hides the 'view more' */
$(this).hide();
/* Displays the rest of the text */
$(this).parents(my_div).find('.rest_of_text').show();
});
}
});
});
Now, about the substr function. This function cuts a string (in this case, the html inside our div) and has two parameters:
- The starting point (every string starts at 0)
- The ending point (optional)
first we did this:
var short_text = $(this).html().substr(0, max_length);
Let's say, for example, the string inside our div was "Hello, I'm an awesome div" and our maxlength equals 16. In that case, **shorttext** would be equal to:
Hello, I'm an awe
Given that, an using substr to get the rest of the string, we would use:
var long_text = $(this).html().substr(max_lenght);
And it is the same as:
some div
Then, when we merge those two we get the full message...
Hello, I'm an awesome div
|-- short text -||-long text-|
*UPDATE * -- Ajax request
Now, for a practical example with ajax, the code would be almost the same. All you'd have to do is a $.get() request.
$.get('your_file.txt', function(data) {
// Same instructions from above
var data_short = data.substr(0, max_length);
var data_long = data.substr(max_length);
// ...As I said, same instructions from above.
}); //End of the $.get() request.
Written by Héctor Salazar
Related protips
3 Responses
Again me, can you make an Ajax call using Jquery? =)
PD: we're Living in the same city
Your code works well, but there's a typo in
$(this).find('a.viewmorebutton').click(funcion(event)
It should be FUNCTION. Took me some time to find out what was going wrong!
Wow, 1+ year later and I didn't see that, thanks!