VladJ VladJ - 7 months ago 17
Javascript Question

How can I make a div disappear and reappear on button click?

I have this code so far :

$(document).ready(function(){

$('#panel').hide();

$("button").click(function(){
$("#panel").fadeIn(3000);
});
});


HTML:

<center><button class="button" id="button">CLUJ</button></center>

<div class="panel" id='panel'>
<p>
Universitatea Alexandru Ioan Cuza din Iasi <br><br>
Universitatea din Craiova <br><br>
Universitatea din Bucuresti <br><br>
Universitatea Babes-Bolyai din Cluj-Napoca <br><br>
</p>
</div>


1.The div doesn't hide;
2.How can I make the div appear and disappear on button click? (Something like an accordion)

Answer

You can use jQuery's fadeToggle like this:

$(document).ready(function(){
    $("#button").click(function(){
        $("#panel").fadeToggle(3000);
    });
});

And to initially hide the div, just add this to your css:

#panel    {
    display:none;
}

JSFIDDLE: https://jsfiddle.net/bgepfuhb/3/


For more than one panel, you can add unique IDs like this:

    <center><button class="button" id="buttonA">CLUJ</button></center>
    <div class="panel" id='panelA'>
        <p>....</p>
    </div>

    <center><button class="button" id="buttonB">CLUJ</button></center>

    <div class="panel" id='panelB'>
        <p>....</p>
    </div>

    <center><button class="button" id="buttonC">CLUJ</button></center>

    <div class="panel" id='panelC'>
        <p>....</p>
    </div>

JSFIDDLE: https://jsfiddle.net/bgepfuhb/7/

Comments