1

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";
    }
}

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Shorthand e.display = e.display == "block" ? "none" : "block";
1

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";
}

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.