Search This Blog

Monday 5 November 2012

A "Read more/Hide" link with jQuery

Sometimes you have long text and few space to show it, with jQuery and CSS is very simple to hide part of the text and create a "Read more" link.
So, this is the HTML, please note that the value of links DIV ID is replicated as CLASS in the links and in the extra text:
Lorem ipsum dolor sit amet
(Read more...) (Hide...)
Praesent commodo, tellus vehicula facilisis laoreet, enim tellus sagittis metus, vel posuere risus tellus vel quam. Praesent fermentum, risus nec sagittis volutpat
Nullam fringilla hendrerit nisi et varius.
(Read more...) (Hide...)
Mauris blandit ullamcorper purus, sit amet imperdiet tortor suscipit et. Nulla luctus magna eu dolor tempor pharetra. Sed egestas, massa id consectetur
With CSS we hide one of the links and the extra text.

Then the jQuery!
Clicking on a link with CLASS "read"
$(".read").click(
We get the ID in the parent DIV
var i=$(this).parent().attr("id");
Then we switch the link with the function .toggle():
$("a."+i).toggle();
And we show the text with .slideToggle(), which creates a more pleasing effect than .toggle().
$("div."+i).slideToggle("slow");
At least our jQuery call will appear like this:
$(".read").click(
    function () 
    {
    var i=$(this).parent().attr("id");
    $("a."+i).toggle(); 
    $("div."+i).slideToggle("slow");
  });
See the demo:

No comments:

Post a Comment