Show and hide a div by clicking the same link

Asked

Viewed 4,072 times

2

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

2 answers

4


Give that div a class and use the classList.toggle in the element in question.

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 that with display (example LINK TO) or with opacity (example link B), there are differences between the two.

Take a look here to read more about the differences: /a/44684/129

With jQuery:

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

using .toggle()

The .toggle() shows and hides without CSS classes. Uses display: none and block jsFiddle: http://jsfiddle.net/a5mfrn7s/2/

using toggleclass()

The toggleclass() adds and removes classes, as in the example above pure Javascript with CSS classes (and better practice than the toggle()).
jsFiddle: http://jsfiddle.net/a5mfrn7s/1/

  • 1

    Thank you very much guy

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.