Home > Net >  Onclick Event Targeting Whole Document
Onclick Event Targeting Whole Document

Time:10-09

My onclick event is firing when I click anywhere on the document.

If I make an inline onclick event in HTML, the onclick works as expected.

My goal is to make it so that code() only executes when I click on the #top element.

top = document.querySelector("#top");
let topActive = false;
top.onclick = code;
function code () {
    console.log("This executes if I click anywhere on the document");
}
* {
    margin: 0;
    padding: 0;
}

body {
    width: 100%;
    min-height: 100vh;
}

.container {
    height: 100vh;
    display: grid;
    grid-template-rows: 1fr 1fr;
    grid-template-columns: 1fr;
}

#top {
    cursor: pointer;
    background-color: #5b6078;
}

#bottom {
    cursor: pointer;
    background-color: #24273a;
}
<html>
    <head>
        <title>Audio</title>
        <link rel="stylesheet" href="index.css" />
    </head>
    <body>
        <div >
            <div id="top" onclick="console.log('This executes only when I click #top')"></div>
            <div id="bottom"></div>
        </div>
        <script src="test.js"></script>
    </body>
</html>

CodePudding user response:

On the top level, top already exists as an identifier - it refers to window.top, which points to the top-level window (unless you're dealing with iframes already, this is the window itself). So when you do

top = document.querySelector("#top");

it silently fails, because window.top is not reassignable. (Consider using strict mode instead; it'll turn silent failures into explicit errors, which are easier to debug.)

Then when you do

top.onclick = code;

because top is the same as window.top, and window.top is just the window (in most cases), the above is equivalent to

window.onclick = code;

So any click on the window runs the handler.

Use a different variable name, or run the code inside an IIFE (and make sure to declare your variables with const or let or var in the future).

const topDiv = document.querySelector("#top");
let topActive = false;
topDiv.onclick = code;

function code() {
  console.log("OK now");
}
* {
  margin: 0;
  padding: 0;
}

body {
  width: 100%;
  min-height: 100vh;
}

.container {
  height: 100vh;
  display: grid;
  grid-template-rows: 1fr 1fr;
  grid-template-columns: 1fr;
}

#top {
  cursor: pointer;
  background-color: #5b6078;
}

#bottom {
  cursor: pointer;
  background-color: #24273a;
}
<div >
  <div id="top" onclick="console.log('This executes only when I click #top')"></div>
  <div id="bottom"></div>
</div>

CodePudding user response:

top function needs to be called in onlick=""

  • Related