Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Toggle a div's visibility by using a button click

Below is my javascript code which i used to show a div when clicked on a button.

How can I hide it when clicked again? And then on clicking it, div should be visible again?

<script type="text/javascript"> var _hidediv = null; function showdiv(id) {     if(_hidediv)         _hidediv();     var div = document.getElementById(id);     div.style.display = 'block';     _hidediv = function () { div.style.display = 'none'; }; } </script> 
like image 432
user2827600 Avatar asked Sep 29 '13 03:09

user2827600


People also ask

How do you toggle element visibility?

To toggle a div visibility in jQuery, use the toggle() method. It checks the div element for visibility i.e. the show() method if div is hidden. And hide() id the div element is visible. This eventually creates a toggle effect.

How do you hide and show on click?

Projects In JavaScript & JQuery To show and hide div on mouse click using jQuery, use the toggle() method. On mouse click, the div is visible and on again clicking the div, it hides.

How do you hide a div when a button is clicked?

To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .


2 Answers

To switch the display-style between block and none you can do something like this:

function toggleDiv(id) {     var div = document.getElementById(id);     div.style.display = div.style.display == "none" ? "block" : "none"; } 

working demo: http://jsfiddle.net/BQUyT/2/

like image 89
Gigo Avatar answered Sep 20 '22 13:09

Gigo


In case you are interested in a jQuery soluton:

This is the HTML

<a id="button" href="#">Show/Hide</a> <div id="item">Item</div> 

This is the jQuery script

$( "#button" ).click(function() {     $( "#item" ).toggle(); }); 

You can see it working here:

http://jsfiddle.net/BQUyT/

If you don't know how to use jQuery, you have to use this line to load the library:

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script> 

And then use this line to start:

<script> $(function() {     // code to fire once the library finishes downloading. }); </script> 

So for this case the final code would be this:

<script> $(function() {     $( "#button" ).click(function() {         $( "#item" ).toggle();     }); }); </script> 

Let me know if you need anything else

You can read more about jQuery here: http://jquery.com/

like image 25
Jan Avatar answered Sep 19 '22 13:09

Jan