Read more / less toggle
by sambaldwin
HTML
<div class="wrap">
<p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget
lacinia odio sem nec elit.
</p>
<a class="readmorebtn">Read more</a>
<p class="more">Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.
Curabitur blandit tempus porttitor. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Maecenas faucibus mollis interdum. Etiam porta sem malesuada
magna mollis euismod. Praesent commodo cursus magna, vel scelerisque nisl
consectetur.
</p>
</div>
<div class="wrap">
<p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget
lacinia odio sem nec elit.
</p>
<a class="readmorebtn">Read more</a>
<p class="more">Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.
Curabitur blandit tempus porttitor. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Maecenas faucibus mollis interdum. Etiam porta sem malesuada
magna mollis euismod. Praesent commodo cursus magna, vel scelerisque nisl
consectetur.
</p>
</div>
CSS
body {
font-family:Helvetica Neue;
font-size:100%;
line-height:1.4em;
font-weight:500;
margin:20px;
}
p {
margin:1.4em 0;
}
p.more {
display:none;
}
a.readmorebtn {
cursor:pointer;
}
a.readmorebtn:hover {
border-bottom:1px black solid;
}
.wrap {
border-bottom: 1px solid #ccc;
}
}
JavaScript
// These variables exist at the top for easy access = you don't have to read through the code to find where to change moreText, lessText, or moreButton..
var moreText = "Read more",
lessText = "Read less",
moreButton = $("a.readmorebtn");
// Click event....
moreButton.click(function () {
// Cache the clicked element.
var $this = $(this);
// Give the clicked element text...
// There's a ternary if statement inside the .text(), which translates to:
// if ( $this.text() == moreText ) {
// lessText
// }
// else {
// moreText
// }
// and to put that to words: If text is more, switch text to less and the other way around.
$this.text( $this.text() == moreText ? lessText : moreText );
// Get the next paragraph with class .more, and slideToggle ( animation ).
$this.next("p.more").slideToggle("fast");
});