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>
This question is related to
javascript
css
html
show-hide
Try following logic:
<script type="text/javascript">
function showHideDiv(id) {
var e = document.getElementById(id);
if(e.style.display == null || e.style.display == "none") {
e.style.display = "block";
} else {
e.style.display = "none";
}
}
</script>
jQuery would be the easiest way if you want to use it, but this should work.
function showHide(){
var e = document.getElementById('e');
if ( e.style.display !== 'none' ) {
e.style.display = 'none';
} else {
e.style.display = '';
}
}
Bootstrap 4 provides the Collapse component for that. It's using JavaScript behind the scenes, but you don't have to write any JavaScript yourself.
This feature works for <button>
and <a>
.
If you use a <button>
, you must set the data-toggle
and data-target
attributes:
<button type="button" data-toggle="collapse" data-target="#collapseExample">
Toggle
</button>
<div class="collapse" id="collapseExample">
Lorem ipsum
</div>
If you use a <a>
, you must use set href
and data-toggle
:
<a data-toggle="collapse" href="#collapseExample">
Toggle
</a>
<div class="collapse" id="collapseExample">
Lorem ipsum
</div>
You can easily do it with jquery toggle. By this toggle or slideToggle you will get nice animation and effect also.
$(function(){_x000D_
$("#details_content").css("display","none");_x000D_
$(".myButton").click(function(){_x000D_
$("#details_content").slideToggle(1000);_x000D_
}) _x000D_
})
_x000D_
<div class="main">_x000D_
<h2 class="myButton" style="cursor:pointer">Click Me</h2>_x000D_
<div id="details_content">_x000D_
<h1> Lorem Ipsum is simply dummy text</h1> _x000D_
<p> of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>_x000D_
</div>_x000D_
</div>
_x000D_
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/
with JQuery .toggle()
you can accomplish it easily
$( ".target" ).toggle();
Source: Stackoverflow.com