Skip to content

Instantly share code, notes, and snippets.

@raazon
Created April 10, 2019 10:56
Show Gist options
  • Save raazon/65bc58a71e3ddd1605245dd38c066c86 to your computer and use it in GitHub Desktop.
Save raazon/65bc58a71e3ddd1605245dd38c066c86 to your computer and use it in GitHub Desktop.
jQuery Read More/Less Toggle
// document onload
$(document).ready(function() {
// Configure/customize these variables.
var showChar = 100; // How many characters are shown by default
var ellipsestext = "...";
var moretext = "Show more >";
var lesstext = "Show less";
$('.ic_read_more').each(function() {
var content = $(this).html();
if(content.length > showChar) {
var c = content.substr(0, showChar);
var h = content.substr(showChar, content.length - showChar);
var html = c + '<span class="moreellipses">' + ellipsestext+ '</span> <span class="morecontent">' + h + '</span> <a href="" class="morelink">' + moretext + '</a>';
$(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('.ic_read_more').find('.moreellipses').toggle();
$(this).parent('.ic_read_more').find('.morecontent').toggle();
return false;
});
});
// custom reusable function
function ic_readmore_readless_Toggle(morediv=".ic_read_more", showChar = 100, ellipsestext = "...", moretext = "Show more >", lesstext = "Show less"){
$(morediv).each(function() {
var content = $(this).html();
if(content.length > showChar) {
var c = content.substr(0, showChar);
var h = content.substr(showChar, content.length - showChar);
var html = c + '<span class="moreellipses">' + ellipsestext+ '</span> <span class="morecontent">' + h + '</span> <a href="" class="morelink">' + moretext + '</a>';
$(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('.ic_read_more').find('.moreellipses').toggle();
$(this).parent('.ic_read_more').find('.morecontent').toggle();
return false;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment