jQuery - toggle more / less text

Wednesday, 7 January 2009

This next tutorial is a nice easy implementation of a more / less toggle on a paragraph with text. This can be used in a variety of ways with a few simple changes e.g. expanding a div.

We will have a paragraph with some text in it and a more/less link down the bottom that will change depending on the current state. Basically when there is less text it will say 'more' and when there is more text it will say 'less'.

It's pretty straight forward but quite useful.

This has been tested in Firefox and IE. Be aware the chosen height of my text paragraph will cut-off the text in the middle depending on the browser so will need a bit of fiddling with css when implementing.

Start off with our text paragraph in its 'less' state with the 'more' link showing:

<p id="mytext" style="'width:260px;height:200px;overflow:hidden;'">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Quisque iaculis tincidunt tortor. Nulla turpis dui, gravida non,
varius quis, molestie sit amet, justo. Vestibulum sed elit.
Duis lobortis odio quis nisi. Praesent enim. Sed auctor commodo lectus.
In eget augue a nulla auctor interdum.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Nulla enim turpis, commodo at, feugiat nec, dapibus et, odio. Cras enim risus, sagittis eget,
ultrices quis, eleifend vel, risus. Cras a felis eu urna ornare vulputate.
Pellentesque viverra, lacus vitae tincidunt accumsan, nisi metus feugiat felis,
sed placerat est dolor et eros. Duis cursus. Maecenas sollicitudin, lorem vitae
placerat eleifend, dui elit imperdiet tellus, at convallis sapien orci sed pede.</p>
<a href="#" id="adjust">more</a>

Next we place our toggle function inside our javascript file as such:

$(document).ready(function() {
var adjustheight = 200;
$("#adjust").toggle(function() {
$('#mytext').css('height', 'auto').css('overflow', 'visible');
}, function() {
$('#mytext').css('height', adjustheight).css('overflow', 'hidden');

Nice, straight-forward and effective.

P.S If you are looking for a lorem ipsum generator, this is a good one here.
blog comments powered by Disqus