Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick Function "this" Returns Window Object

Tags:

I've come across a head scratching issue with my JavaScript application.

If I write an element like this:

<li onClick="alert(this.tagName)"></li>

I get "LI."

However if I do this:

<li onClick="foo()"></li>

Where "foo()" is:

function foo(){ alert(this.tagName); }

I get "undefined."

I am away how "this" is supposed to work in regards to attached functions. But, I am baffled because "this" is not picking up the element, but apparently defaulting to "window." I can't figure out why this is happening.

Does anyone have an explanation?

like image 810
Pori Avatar asked Sep 18 '12 22:09

Pori


People also ask

How do you use this function onclick?

onclick = doSomething; The function is copied in its entirety to the onclick property (which now becomes a method). So if the event handler is executed this refers to the HTML element and its color is changed. Thus you use this to the fullest extent.

What is this in onclick function?

The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning messages and many more. Using JavaScript, this event can be dynamically added to any element.

What is difference between Onclick and Onclick?

If you called onclick ( element. onclick() ), you'd call the function attached to it — but not handlers attached with modern methods. E.g., click triggers a fake click; the other lets you set up a handler for clicks.

What is Onclick in Dom?

The onclick event is a DOM event that occurs when a user clicks on an element. The Document Object Model (DOM) is created by the browser when a web page is loaded. This is a data structure representing the page as a series of nodes and objects.


1 Answers

That's because you aren't passing a reference to this in the JavaScript function call. this in the JavaScript function doesn't refer to the same object as in the onClick example. Try this instead:

 <li onClick="foo(this)"></li>

 function foo(item){ alert(item.tagName); }
like image 160
p_strand Avatar answered Nov 29 '22 05:11

p_strand