How to toggle in JavaScript to show hide elements

How to toggle in JavaScript to show hide elements

In toggle function we will work on displaying FAQ’s section once user click on a particular link using JavaScript. If user will click on first faq it will show answer of that once. If user click on other faq question it will hide the first one and show the second answer.

To achieve this functionality is very simple and can be done with just few line of code. To start with we are going to use below html code to toggle the questions.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>FAQs</title>
<link rel=”stylesheet” href=”main.css”>
<script src=”faqs.js”></script>
</head>

<body>
<main id=”faqs”>
<h1>JavaScript FAQs</h1>
<h2><a href=”#” >What is JavaScript?</a></h2>
<div>
<p>JavaScript is a is a browser-based programming language that makes web pages more responsive and saves round trips to the server.
</p>
</div>
<h2><a href=”#”>What is jQuery?</a></h2>
<div>
<p>jQuery is a library of the JavaScript functions that you’re most likely to need as you develop websites.
</p>
</div>
<h2><a href=”#”>Why is jQuery becoming so popular?</a></h2>
<div>
<p>Three reasons:</p>
<ul>
<li>It’s free.</li>
<li>It lets you get more done in less time.</li>

</ul>
</div>
</main>
</body>
</html>
In this html code we have declared one main with id “faqs“. We are going to call this id and use the element inside that id to toggle. We have three H2 tags, and three divs related to that H2 elements to show the questions and answers. So when user will click on the H2 element link it will show and hide or toggle the respective answers.

Now we will create one js file “faqs.js” and write our code of toggle functions. However on the start we will write below code. This will help us to call getElementById multiple times using variable $ without writing the complete text again and again.

var $ = function(id) { return document.getElementById(id); };

Now we will declare window.onload function to initialize the faq and onclick event of each h2 element available inside faqs id.

var faqs = $(“faqs”);
var h2Elements = faqs.getElementsByTagName(“h2”);

So here we are getting faqs id element inside faqs variable and then getting all the h2 elements inside h2Elements using getElementsByTagName. This will give us an array of 3 values. Now we will assign the click event on all the element using for loop like below.

// attach event handler for each h2 tag
for (var i = 0; i < h2Elements.length; i++ ) {
h2Elements[i].onclick = toggle;
}

here for loop will run three times and call the toggle function on click of h2element using javascript. Below code is used to set the focus on first child or div of that particular h2 elements.

// set focus on first h2 tag’s <a> tag
h2Elements[0].firstChild.focus();

Now we will create a toggle function and check which h2 element is clicked and get the div of that element using below code.

var h2 = this; // clicked h2 tag
var div = h2.nextElementSibling; // h2 tag’s sibling div tag
var faqs = $(“faqs”);
var h2Elements = faqs.getElementsByTagName(“h2”);
Now we will run the for loop once again to check which element is active in past and disable that. Once done we will enable the new clicked element.

for (var i = 0; i < h2Elements.length; i++ ) {

// toggle plus and minus image in h2 elements by adding or removing a class
if (h2!=h2Elements[i]) {
h2Elements[i].removeAttribute(“class”);
} else {
h2Elements[i].setAttribute(“class”, “minus”);
}




// toggle div visibility by adding or removing a class
if (div!=h2Elements[i].nextElementSibling) {
h2Elements[i].nextElementSibling.removeAttribute(“class”);
} else {
h2Elements[i].nextElementSibling.setAttribute(“class”, “open”);
}

}

In this case we are simply removing the class if element is active in past and adding new class to the clicked element.

Below is the complete code of JavaScript once again with css used so you get the idea of class we have used to add and remove.

“use strict”;
var $ = function(id) { return document.getElementById(id); };

// the event handler for the click event of each h2 element
var toggle = function() {

var h2 = this; // clicked h2 tag
var div = h2.nextElementSibling; // h2 tag’s sibling div tag

var faqs = $(“faqs”);
var h2Elements = faqs.getElementsByTagName(“h2”);

for (var i = 0; i < h2Elements.length; i++ ) {

// toggle plus and minus image in h2 elements by adding or removing a class
if (h2!=h2Elements[i]) {
h2Elements[i].removeAttribute(“class”);
} else {
h2Elements[i].setAttribute(“class”, “minus”);
}

// toggle div visibility by adding or removing a class
if (div!=h2Elements[i].nextElementSibling) {
h2Elements[i].nextElementSibling.removeAttribute(“class”);
} else {
h2Elements[i].nextElementSibling.setAttribute(“class”, “open”);
}

}

};

window.onload = function() {

// get the h2 tags
var faqs = $(“faqs”);
var h2Elements = faqs.getElementsByTagName(“h2”);

// attach event handler for each h2 tag
for (var i = 0; i < h2Elements.length; i++ ) {
h2Elements[i].onclick = toggle;
}

// set focus on first h2 tag’s <a> tag
h2Elements[0].firstChild.focus();

};

CSS file for html code. Please note we are using plus and minus sign images to display before the h2 element. You can use your own images for the same and save that under images folder to work with our css.

* {
margin: 0;
padding: 0;
}
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 87.5%;
width: 650px;
margin: 0 auto;
border: 3px solid blue;
padding: 15px 25px;
}
h1 {
font-size: 150%;
}
h2 {
font-size: 120%;
padding: .25em 0 .25em 25px;
cursor: pointer;
background: url(images/plus.png) no-repeat left center;
}
h2.minus {
background: url(images/minus.png) no-repeat left center;
}
a {
color: black;
text-decoration: none;
}
a:focus, a:hover {
color: blue;
}
div {
display: none;
}
div.open {
display: block;
}
ul {
padding-left: 45px;
}
li {
padding-bottom: .25em;
}
p {
padding-bottom: .25em;
padding-left: 25px;
}

Share this post

Comment (1)

  • Brian Reply

    Great tutorial with example. Loved it alot.

    November 23, 2018 at 2:20 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.