Home > Blockchain >  addEventListener Function wont Execute [duplicate]
addEventListener Function wont Execute [duplicate]

Time:09-22

can't for the life of me figure out why this doesn't work

document.querySelector('body').addEventListener('click', function () {
    console.log('wow')
});

I dont get any error, but nothing is logged onclick.

CodePudding user response:

There is no content in the body, so it has a height of 0px. You can set its height:

document.querySelector('body').addEventListener('click', function() {
  console.log('wow')
});
html,
body {
  height: 100%;
}

Or attach the click event listener to the document instead:

document.addEventListener('click', function() {
  console.log('wow')
});

CodePudding user response:

Probably because you are clicking outside of your body element. Check your body in inspect and click inside it.

document.querySelector('body').addEventListener('click', function () {
    alert('wow')
});
div { 
  background: black;
  color: white;
  }
<div>Body</div>

  • Related