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>
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.
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.
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.
Yes, you can call two JS Function on one onClick. Use semicolon (';') between both the functions.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With