- «onclick» and «this» in javascript
- 2 Answers 2
- about this values.
- Inline event handlers in HTML
- What’s «this» in JavaScript onclick?
- 8 Answers 8
- onclick Event
- Mouse Events
- See Also:
- Tutorial:
- Syntax
- Technical Details
- More Examples
- Click me to change my color.
- Click me to change my color.
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
«onclick» and «this» in javascript
In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever. https://www.w3schools.com/js/js_arrow_function.asp
const arrayBtn = document.querySelector(".arrowFunc"); const regBtn = document.querySelector(".regFunc"); hello = () => console.log("i am arrow function" + this); function hiii() < console.log("i am regular function" + this); >arrayBtn.addEventListener("click", hello); regBtn.addEventListener("click", hiii);
[Log] i am arrow function[object Window]
[Log] i am arrow function[object Window]
[Log] i am regular function[object Window]
[Log] i am regular function[object HTMLButtonElement]
[Log] Window , …>
[Log]
What’s to understand? You wrote how this context is interpreted already. this , in a regular function, within the method (function) of an Object, refers to the Object, which in the case of an Event is the Element. So the function assigned to the onclick of a Element is the method, and the button is the Object. this within an Arrow function scopes up to wherever your last scope is, global if not within a class or constructor. Note that a constructor is a function. It only becomes an Object upon calling new on it.
2 Answers 2
about this values.
- Arrow functions capture and always use their lexical this value, meaning the one that was in effect when their arrow function expression was evaluated. Evaluation usually occurs when executing an assignment operation or when calculating parameter values for a function call which has arrow functions in its argument list.
- Arrow functions cannot be used as constructors.
- Non arrow functions called as constructors using new (or super when extending a class) see the object under construction as their this value.
- Bound functions save and use a this value supplied as the first argument to the bind method of another function.
- Bound functions ignore their saved this value if called as constructors — but this is rare enough to be considered an edge case and is not generally recommended.
- Binding an arrow function has no effect on its this value but could be used to predefine a set of parameter values.
- Functions called using either their call or apply object methods take their this value from the (first) thisValue argument supplied to call or apply , subject to JavaScript mode:
- In strict mode null or undefined values provided for thisValue are used as the function’s this value. In sloppy mode however, null or undefined are replaced by window before making the call.
- Arrow and bound functions can be called using these methods (e.g. to supply arguments) but use their own recorded this value.
- Provided none of the preceding rules apply, functions explicitly called as a method of an object use the object as their this value. E.G. in a call of form
someObject.methodName( optionalArgumentList)
function a () < "use strict"; console.log("in strict mode functions the default this is ", this); >; let b = function() < console.log("but in non strict mode, the default this is ", this === window ? "window" : this ); >a(); // undefined b(); // window
- Code provided as a text string in calls to the global Function constructor, SetTimeout , related timer calls, and event attributes in HTML source, is treated as a «script» in its own right and creates a function that
- operates in sloppy mode if strict mode is not invoked by the supplied source code,
- operates in strict mode if strict mode is invoked in the source.
While this alters the default this value of the function, is is also an edge case because none of these methods of creating a function is recommended when writing maintainable code.
- Direct calls to eval inherit this from the calling context unless the evaluated code invokes strict mode — in which case this is undefined during code evaluation.
- Indirect calls to eval use window (i.e. the global object) as this even if they invoke strict mode (Ref.)
This is also an edge case since because of its dangers, eval should never be used because you can.
Inline event handlers in HTML
Event handler content attributes in an HTML tag of the form
are converted into event handler functions by the HTML parser using steps equivalent to
- Save the text as the attribute’s string value.
- Use the JavaScript parser/compiler to create an event handler function from the text by including it in a template of form
- HTML onEventName attributes predate both standardization of the DOM and the introduction of addEventListener : Handlers created by the HTML parser have a legacy scope chain that minimally searches the element the event attribute belongs to, a surrounding form element if any, and the document object before reaching the global object when looking up names — which can result in obscure bugs.
Why with inline onlick, we have to write onclick=»hello()», but in JS, we should write btn.onclick=hello or btn.addEventListener(‘click’,hello);
The HTML event handler attribute is used as the body code of a event handler function created by the HTML parser. To call hello , attribute text must provide the source code to make the call, as in e.g. hello() .
In JS, setting an onclick to a function object, or calling addEventListener with a function as the second parameter, adds the function to a map of handlers associated with the element. If parentheses are placed after the function name, using onclick as an example:
the function is called and an attempt is made to use its return value as a handler function — and if the return value is not a function little happens. Most often this is a mistake and not the desired outcome. question 2
For regular function, why with inline onclick, «this» refers to window, but with js call, «this» refers to button.
Inside the event handler function created from an inline onclick attribute, this does refer to the button. If you call out to another function with code like hello() , you are making an unqualified call to it, so the called function uses its default this value — i.e. window if the called function operates in sloppy mode.
Following on from «Inline event handlers in HTML», you could pass on this (referring to the button) and the event object as a parameter values if you wanted to:
Handler functions provided in JavaScript go directly into the element’s map of event handlers and are called by the event system with the button as their this value (probably using call or apply , since handlers added with addEventListener aren’t maintained as element property values).
Creates the event handler function
function onclick(event) < function tes()< console.log(this) >tes() >
Strict mode was not invoked in the button tag’s event attribute text, so both onclick and tes are in sloppy mode. tes is called without qualification, so it uses and logs its default this value which is window .
In regards to «about this values», none of rules 1 — 5 apply, so rule 6 comes into effect.
creates a handler function
which is called with the button element as its this value by the event system as it would for any other handler. console.log is showing the outer HTML for the button in the log. If you change this to a string, the log will tell you its an HTMLButtonElement element instead:
What’s «this» in JavaScript onclick?
@JMCF125 He managed to be useful anyway. I Googled for how to get the element that was clicked on in an onclick event, and ended up here, where I found the answer.
@J3STER The «javascript:» prefix is incorrect in onclick. You can find the explanation in Tim Down’s answer below.
8 Answers 8
In the case you are asking about, this represents the HTML DOM element.
It refers to the element in the DOM to which the onclick attribute belongs:
The value of event handler attributes such as onclick should just be JavaScript, without any «javascript:» prefix. The javascript: pseudo-protocol is used in a URL, for example:
You should use the onclick=»func(this)» form in preference to this though. Also note that in my example above using the javascript: pseudo-protocol «this» will refer to the window object rather than the element.
Interesting downvote, although I suppose strictly speaking this answer only offers advice around the question rather than directly answering the question.
@Dave: Fair enough. By the time I wrote this the main question was already answered. My answer should probably have been a comment but I suspect I may not have had enough rep to add a comment at the time. Live and learn.
In JavaScript this refers to the element containing the action. For example, if you have a function called hide() :
Calling hide with this will hide the element. It returns only the element clicked, even if it is similar to other elements in the DOM.
For example, you may have this clicking a number in the HTML below will only hide the bullet point clicked.
onclick Event
The onclick event occurs when the user clicks on an HTML element.
Mouse Events
Event | Occurs When |
---|---|
onclick | The user clicks on an element |
oncontextmenu | The user right-clicks on an element |
ondblclick | The user double-clicks on an element |
onmousedown | A mouse button is pressed over an element |
onmouseenter | The pointer is moved onto an element |
onmouseleave | The pointer is moved out of an element |
onmousemove | The pointer is moving over an element |
onmouseout | The mouse pointer moves out of an element |
onmouseover | The mouse pointer is moved over an element |
onmouseup | The mouse button is released over an element |
See Also:
Tutorial:
Syntax
In JavaScript, using the addEventListener() method:
Technical Details
Bubbles: | Yes |
---|---|
Cancelable: | Yes |
Event type: | MouseEvent |
Supported HTML tags: | All exept: , , , , , , , , , , and |
More Examples
Click a to display the date:
Click a element to change the text color:
Click me to change my color.
Another example on how to change the color of an element:
Click me to change my color.
Click to copy text from one input field to another:
function myFunction() document.getElementById(«field2»).value = document.getElementById(«field1»).value;
>
How to assign an «onclick» event to the window object:
function myFunction() document.getElementsByTagName(«BODY»)[0].style.backgroundColor = «yellow»;
>
Use onclick to create a dropdown:
function myFunction() document.getElementById(«myDropdown»).classList.toggle(«show»);
>
Browser Support
onclick is a DOM Level 2 (2001) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.