Window.onclick runs the function immediately


I have a button that calls a function onclick. The purpose of the button is to assign a function to window.onclick. The problem is that the function that I have assigned to window.onclick, just by pressing the button, runs immediately... And that's not what I'm trying to accomplish. As far as I know im not calling the function, im just assigning it to the window.onclick by reference or whatever you prefer to call it.

This is what I want to happen:

The first press on the button should just "active" the function. Not call it immediately. Why does this happen with the code below? Its like I activate the "window onclick function", and then it reacts directly to the previous click on the button.
However, when I change onclick to onmousedown it works the way I want it. I want to understand why it runs immediately without me calling it.

Here is the code:

<button onclick="activateWindowOnClick()">ACTIVATE</button>

function activateWindowOnClick () {
window.onclick = windowfunction;

function windowfunction() {
alert('This should not be displayed now. I have not clicked on the window after activating the function');



This happens because the event doesn't stop at the button, it bubbles up to its parent, then its parent's parent, etc, until it reaches window. This is called event propagation.

So what happes is clicking the button sets up the window onclick and the event bubbles up and immediately executes the window onclick.

In order to prevent this you have to call Event.stopPropagation like so:

function activateWindowOnClick(event) {
window.onclick = windowfunction;

Also, using onclick in HTML is quite outdated. You should put an ID on that element and then fetch it with Javascript using document.querySelector.


Sound great, but why dont I have the same problem with onmousedown?


It must have the same attribute to affect its parent?


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.