-3

I have a div element and I set its display to none in css. Then in my main.js file I wanted to change the display to block after I click on a button like so:

    var btnClick = document.getElementById("my-btn");

    btnClick.addEventListener("click", function() {
 var myDiv = document.getElementById("my-div");

 if (myDiv.style.display == "none") {
  myDiv.style.display = "block";
 }
    else {
   myDiv.style.display = "none";
  alert("here")
 }
    });
#my-div {   
    height: 50px;
    width: 50px;
    background-color: red;
    display: none;
  }
<div id="my-div"></div>

<button id="my-btn">Click</button>

But when I click on the button nothing happens.

Afn
  • 1
  • 1
  • 1
    see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style#Getting_style_information and http://stackoverflow.com/q/2664045/6303733 – gcampbell Aug 09 '16 at 12:38

2 Answers2

0

It should be myDiv.style.display condition

var btnClick = document.getElementById("my-btn");

btnClick.addEventListener("click", function() {
    var myDiv = document.getElementById("my-div");
    if (myDiv.style.display == "none") {
       myDiv.style.display = "block";
    }
    else{
        myDiv.style.display = "none";
    }
});
Özgür Ersil
  • 6,909
  • 3
  • 19
  • 29
  • Explanation for the down vote - you cannot access the `style.display` if it was defined by css. – Dekel Aug 09 '16 at 12:45
0

You had a problem with your code in myDiv.display, as there is no display property to your div (it's a property of style), however - even with the style you cannot have immediate access to the display property.

You cannot get the style definition from the css using element.style.X. In order to do so you need to use window.getComputedStyle(element, null).getPropertyValue

Here is an example:

var btnClick = document.getElementById("my-btn");
btnClick.addEventListener("click", function() {
  var myDiv = document.getElementById("my-div");
  if (myDiv.style.display == "none" || window.getComputedStyle(myDiv, null).getPropertyValue("display") == "none") {
      myDiv.style.display = "block";
  } else {
    myDiv.style.display = "none";
  }
});
#my-div {
  height: 50px;
  width: 50px;
  background-color: red;
  display: none;
}
<div id="my-div">
</div>

<button id="my-btn">Click</button>

There is a good reason for using external libraries (like jquery) for stuff like that :)

Dekel
  • 60,707
  • 10
  • 101
  • 129