The onclick function is called, although it is not set in the button

I have the following code. I could not understand why the click event occurs, even if I did not set a function for the onclick attribute of the button.

var x = 0;
var onclick = function() {
  console.log("x = " + ++x);
};
<button type="button" onclick="">Click</button>
Run codeHide result
+6
source share
2 answers

Well, you set a global variable onclickthat translates into a global windowproperty object onclick. This is basically the same thing that you should install it directly:

window.onclick = function() {
    console.log("x = " + ++x);
};

And since you set the click event for the entire object window, it will fire not only when the button is clicked, but also when you click on something inside your document (if the event is not stopped).

+8
source

@dfsq, window.onclick, var onclick=. :

var onerror = function() {
  console.log("ERROR HAPPENED!");
};
<button type="button" onclick="ThisFunctionIsNotDefined()">Click</button>
Hide result
0

Source: https://habr.com/ru/post/1016233/


All Articles