2

Im trying to add in a close button for my div. It opens all ok but doesnt close and I cant fathom why ...

The code is here

window.onload = function display() {
  document.getElementById("advert").style.display = "block";
}



function close() {
  document.getElementById("advert").style.display = "none";
}
<div id="advert">
  <div class="advert-content">
    <button class="Close" onclick="close()">&times;</button>
    <p>Content is here</p>
  </div>
</div>
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
T.alcock
  • 31
  • 6

3 Answers3

5

You can't use "close()" as a function name, it seems to be reserved (which makes kind of sense). Just use another name.

window.onload = function display() {
  document.getElementById("advert").style.display = "block";
}



function xclose() {
  document.getElementById("advert").style.display = "none";
}
<div id="advert">
  <div class="advert-content">
    <button class="Close" onclick="xclose()">&times;</button>
    <p>Content is here</p>
  </div>
</div>
sascha10000
  • 1,245
  • 1
  • 10
  • 22
4

Window.close() is a reserved word in JavaScript.

The Window.close() method closes the current window, or the window on which it was called.

When you use that name as your function name, that function is actually overridden by Window.close() and nothing happens.

Change your function name from close to some other name.

window.onload = function display() {
  document.getElementById("advert").style.display = "block";
}


function closeDiv() {
  document.getElementById("advert").style.display = "none";
}
<div id="advert">
  <div class="advert-content">
    <button class="Close" onclick="closeDiv()">&times;</button>
    <p>Content is here</p>
  </div>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

As the other answers have mentioned close is a reserved word, but that only seems to apply to inline JS. You can move the code for the event listener outside of the HTML and still use close as your function name. As an added benefit not-including JS in your HTML is considered good practice.

const button = document.querySelector('.close');
button.addEventListener('click', close, false);

function close() {
  document.getElementById("advert").style.display = "none";
}
<div id="advert">
  <div class="advert-content">
    <button class="close">&times;</button>
    <p>Content is here</p>
  </div>
</div>
Andy
  • 61,948
  • 13
  • 68
  • 95