Friday, March 14, 2014

How to Show/Hide Read More 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:

<div class="section">
<div id="lorem">
Lorem ipsum dolor sit amet
<a class="read lorem" href="">(Read more...)</a>
 <a class="read hide lorem" href="">(Hide...)</a>

<div class="more lorem">
Praesent commodo, tellus vehicula facilisis laoreet,enim tellus sagittis metus, vel posuere risus tellus vel quam. Praesent fermentum, risus nec sagittis volutpat

<div class="section">
<div id="nullam">
Nullam fringilla hendrerit nisi et varius.
<a class="read nullam" href="">(Read more...)</a>
 <a class="read hide nullam" href="">(Hide...)</a>

<div class="more nullam">
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.
<style type="text/css">
.more, .hide{ display:none;}
Then the jQuery!
$(".read").click(function (){
    var i=$(this).parent().attr("id"); //We get the ID in the parent DIV 
    $("a."+i).toggle();  //switch the link with toggle()

Source: You can view the demo @

No comments:

Post a Comment