RSS iconRSS       Email iconEMAIL
vertical spacer

Blog

Using jQuery to hide/show a number of elements with ease

SIMONR85 over in the affiliates4u forum posted a PHP related query. He initially wanted to show 3 products from a database then when a user clicks a "show more" link 30 products would be visible. This can be acheived quite easily in PHP but I personally think jQuery would be much more suited to the job. Using jQuery would cut down on server calls while at the same time presenting more information for search engines.

So here is a crude example:

Product title 1 - Product description 1
Product title 2 - Product description 2
Product title 3 - Product description 3
Product title 4 - Product description 4
Product title 5 - Product description 5
Product title 6 - Product description 6
Product title 7 - Product description 7
Product title 8 - Product description 8
Product title 9 - Product description 9

show more

You can view the HTML of this page to see exactly how this is achieved but basically this is down to a few lines of jQuery and one CSS class.

In the HTML you include all of your products, each one inside of a DIV with the CSS class of each DIV set to hideX.

When the page loads, a line of jQuery hides all DIV's that utilise the class hideX with an index greater than 3 (4th product onwards).

Then a few more lines of jQuery handle the "show more" link functionality. Which then either shows or hides all DIV's that utilise the class hideX with an index greater than 3.

Here is the jQuery/javascript. Thats all there is to it. Just make sure you include a refrence to the jQuery javascript library in the head of your document. Feel free to pick apart the HTML source of this webpage.

<script type="text/javascript">
<!--
$(document).ready(function() {

//hide all divs with an index higher than 3
$("div.hideX :gt(2)").toggle(); //show/hide layers

//handle show more click
$("#show_more_link").click(function(e){

$("div.hideX :gt(2)").toggle(); //show/hide layers
e.preventDefault(); //no link action needed

});

});

//-->  </script>

Leave a Reply