jQuery Show Hide

jQuery is one of the most popularly used frameworks because of it’s simplicity over coding practice, learning and etc. Let us have an example to create hide show effect using jQuery. We can do the same using simple Javascript also. But, the reason for why we are going to use jQuery is as follows.

Simplify the code by using inbuilt functions and thereby reducing the burden from doing all the thing by our own. For example, to hide an element from the browser using Javascript, we have to identify their name or id as,

jQuery provides faster response while working with complex programming like AJAX.

This framework provides guaranteed the same effect in all browsers which is the main problem in Javascript.

By having Javascript library, it covers a bundle of functions like event handling, AJAX, dynamic effect on HTML elements and etc., that are needed while developing web applications.

Example: jQuery Show Hide

In this example, we have two links named expand and collapse to show and hide the list of program one by one. The links are appeared like button by applying class selectors of CSS. So, the links can be created as,

On clicking these link, the event is trigger by using jQuery’s click function with respect to the name of the particular class selector. For example, if we click the collapse link, the following block of jQuery code will be executed.

In the above block, while clicking the collapse link, it will be hidden using jQuery’s hide() method. And then, we are calling fnCollapse() method recursively to hide each item from bottom to top of the list. Once, there are no items found to collapse, then the expand link will be shown using show() method.

Similarly, we can repeat the same for expanding, to show each collapsed item from top to bottom of the list. And the code is as shown below.

We should put the above two event handlers inside the block shown below. This block will perform like window.onload() function of plain Javascript.

$(document).ready(function(){
...
});

We can group the above jQuery code snippet into a single Javascript file and save it as jquery.showhide.js to include it into the HTML page. Before that, we need to download the latest version of jQuery library file from jQuery official website. Or we can use it from the internet by specifying it’s URL in the src attribute of the <script> tag. So, entire HTML content will look like as follows.