jQuery

Toggle Show/Hide HTML Element

Below is different ways you can show or hide content.

Javascript

Is a function using raw Javascript which is passed an ID of a HTML element. We then use the getElementById function to get the element.

Now we have the element we can see what the current style display is. If it is set to none then we set it to block, if it's set to block then we set it to none.

Just call this function with the ID to toggle between show and hide.

function toggle_div(id) {
     var e = document.getElementById(id);
     e.style.display = ((e.style.display!='none') ? 'none' : 'block');
}

How To Use This Javascript Function

You can choose which function you want to use either raw Javascript or jQuery but you call it the same way.

<a href="#" onclick="toggle_div('toggleDiv');">Click here to toggle the div between show or hide.</a>
<div id="toggleDiv">This is toggle div</div>

jQuery

jQuery

Here is the jQuery version of the above, I am including the jQuery function because the above is done just by calling the toggle method which show how much easier jQuery is to use.

$('.toggleDiv').on('click', function(){
    this.next().toggle();
});

How To Use This jQuery Function

To use the jQuery function all you have to do is make sure that your link has a class of toggleDiv with a div directly after.

<a href="#" class="toggleDiv">Click here to toggle the div between show or hide.</a>
<div>This is toggle div</div>
Back to top

Fastest WordPress Hosting With WPEngine

Stunning speed, powerful security, and best-in-class customer service. At WP Engine.

Risk free for 60 days