Show and hide a div by clicking on the same link

2

How do I show a div when I click on a link and hide again when I click on the same link?

    
asked by anonymous 29.06.2015 / 23:24

2 answers

4

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

With jQuery:

(if you need to ... in this case the less jQuery is better.)

using .toggle()

.toggle() shows and hides without CSS classes. Uses display: none and block jsFiddle : link

using toggleclass()

toggleclass() adds and removes classes, as in the example above pure JavaScript with CSS classes (and best practice than toggle() ). jsFiddle : link

    
29.06.2015 / 23:33
1

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();
    });
});

JSFIDDLE

    
29.06.2015 / 23:43