0

Button which opens modal doesn't work properly. I can close modal, but can't open because button doesn't work.

Also modal opens at once, but should be originally closed. And only after my click on open-button modal shall open.

My codepen to see it at work

var modal = document.getElementsByClassName("modal-inner");
var btn = document.getElementsByClassName("open-button");
var close = document.getElementsByClassName("close-button")[0];

btn.onclick = function () {
    modal[0].style.display = "block";
}

close.onclick = function () {
    modal[0].style.display = "none";
}
unknown
  • 21
  • 2

1 Answers1

2

You have the button with id "open-button" but are using getElementsByClassName.

Either use getElementById instead or change the button's class to "open-button" instead

var modal = document.getElementsByClassName("popup-inner");
var btn = document.getElementById("open-button");
var close = document.getElementsByClassName("close-button")[0];

btn.onclick = function () {
    modal[0].style.display = "block";
}

close.onclick = function () {
    modal[0].style.display = "none";
}
.popup-inner {border: 1px solid black; height:200px; width:400px; background-color: pink;}
p {text-align: center; font-size: 36px;}
.close-button { position: relative; z-index: 100; float:right; margin-right:5px; margin-top: 5px;}
<button id="open-button">click on me</button>
<div class="popup-inner">
  <button class="close-button">X</button>
  <p>My modal</p>
</div>
GrafiCode
  • 3,307
  • 3
  • 26
  • 31
rsedlr
  • 100
  • 2
  • 14