Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function "onclick" is called even though it is not set in button

I have following code. I haven't been able able to figure out why click event occurs even though I haven't set the function to onclick attribute of button.

var x = 0;
var onclick = function() {
  console.log("x = " + ++x);
};
<button type="button" onclick="">Click</button>
like image 636
Barun Avatar asked Apr 01 '17 08:04

Barun


People also ask

Is Onclick only for buttons?

onclick is not exclusive to buttons. You can also use onclick in plain JavaScript. Here is an example of a JavaScript onclick method: var item = document.

What is the function of Onclick?

The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.

What is the difference between Onclick and Onclick?

onClick will work in html, but if you're defining the handler in JS, you need to use the lowercased onclick. in XHTML, HTML attributes are case sensitive.

Can we call two functions onclick of button?

Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions.


1 Answers

Well you set global variable onclick, which translates to global object window property onclick. This is basically the same as if you were to set it directly:

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

And because you have set click event on entire window object, it will fire not only on button click but on click on anything within your document (unless event propagation is stopped).

like image 147
dfsq Avatar answered Oct 15 '22 13:10

dfsq