jQuery - Creating a accoridan effect using jQuery

Senario:  To show a paragraph when the respective heading is clicked and all other paragraphs should be collapsed.

Using jQuery we can easily create the above effect in few line itself. The effect is usually known as the accordian effect.

jQuery Accordian

To get the above effect, we use two things from jQuery, the .next() , toggle() and .hide()

Let us say the following way our HTML body is set:
<body>
<h1>Toggle paragraphs by clicking headings</h1>
<hr>
<h2>jQuery</h2><
p>jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax..</p>

<h2>Angular</h2>
<p>Angular is a TypeScript-based free and open-source web application framework led by the Angular Team at Google </p>

<h2>nodeJS</h2>
<p>Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser</p>

<h2>JavaScript</h2>
<p>JavaScript, often abbreviated as JS, is a programming language that conforms to the ECMAScript specification</p>
</body>

What we need to do is to associate click with the heading, and hide the next paragraph. (note we will hide all paragraphs before hand using css itself)

Firs hide all paragraphs using css style

<style>      p{display:none}     </style>

The following jQuery code will do our work.

<script>  

    $( "h2" ).click(function(){ $("p").hide(); $(this).next().toggle("slow");  }); 

</script> 

In the above code, when we click on any h2 tag, first we hide all the paragraphs, just to make sure no other paragraphs are open, the second line makes sure the next item is selected from the heading which was clicked,  i.e the decribing paragraph, and then we use the toggle() to make it visible again.

 

Main category

Add new comment

Filtered HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
CAPTCHA
Enter the characters shown in the image.
Are you a robot?
Address

OpenSourceCook.in
"Natraj"  Bungalow,
Colony No.7,  Sr.No. 38.
(Lane Behind Sai Baba Mandir)
Kale Borate Nagar, Hadapsar,
Pune - 411028.
Get Directions