andyduly98
andyduly98

Reputation: 89

How to show/hide a div in javascript?

When i click the button i want the div to show, and when i click the button again i want it to disappear. What am i doing wrong?

<button type="button" onclick="myFunction()">Click Me!</button>

<div id="Dglow" class="Dglow">
    Glow
</div>

<script>
function myFunction() {
    var e = document.getElementById("Dglow").style.display;
    if (e == "none")
        e = "block";
    else {
        e = "none";
    }
}

Upvotes: 1

Views: 51

Answers (3)

user3835115
user3835115

Reputation:

Have you considered using Jquery? If so heres what you need.

$(document).ready(function(){
    $("#button").click(function(){
        $("#Dglow").toggle();
    });
});

You would need to give your button an id for this though.

Upvotes: 1

Joy Biswas
Joy Biswas

Reputation: 6527

Actually document.getElementById("Dglow").style.display returns a string and according to Left hand assignment rule you cannot store anything to that string, since that string is not a variable/object now ie not a reference to DOM anymore

You can do is

var e = document.getElementById("Dglow").style;
if(e.display == "none")
   e.display = "block";
else{
   e.display = "none";
}

Upvotes: 1

dfsq
dfsq

Reputation: 193261

You should compare and change element's display property:

function myFunction() {
    var e = document.getElementById("Dglow").style;
    if (e.display == "none") {
        e.display = "block";
    } else {
        e.display = "none";
    }
}
<button type="button" onclick="myFunction()">Click Me!</button>

<div id="Dglow" class="Dglow">Glow</div>

Upvotes: 1

Related Questions