How do I show a div when I click on a link and hide again when I click on the same link?
How do I show a div when I click on a link and hide again when I click on the same link?
Give this div a class and use classList.toggle
in the element concerned.
Take a look at this example:
var div = document.getElementById('minhaDiv');
var linkA = document.getElementById('linkA');
var linkB = document.getElementById('linkB');
linkA.addEventListener('click', function () {
div.classList.toggle('display');
});
linkB.addEventListener('click', function () {
div.classList.toggle('transicao');
});
* {
float: left;
clear: both;
padding: 20px;
}
.display {
display: none;
}
#minhaDiv {
transition: opacity 1s;
}
.transicao {
opacity: 0;
}
<a href="#" id="linkA">Clica aqui para esconder sem fade (link A)</a>
<a href="#" id="linkB">Clica aqui para esconder con fade (link B)</a>
<div id="minhaDiv">Teste teste teste...</div>
You can do this with display
(example link A ) or with opacity
(example link B ), there are differences between the two.
Take a look here to read more about the differences: link
(if you need to ... in this case the less jQuery is better.)
.toggle()
.toggle()
shows and hides without CSS classes. Uses display: none
and block
jsFiddle : link
toggleclass()
toggleclass()
adds and removes classes, as in the example above pure JavaScript with CSS classes (and best practice than toggle()
). jsFiddle : link
HTML
<a href="javascript:;" class="expander">Link</a>
<div id="minhaDiv">Div que aparece e some</div>
JavaScript (slideToggle)
$(function () {
$('.expander').live('click', function () {
$('#minhaDiv').slideToggle();
});
});