Now Place:2uzhan.com » Javascript: Events and object this

Javascript: Events and object this

Scripting - Client Side @ July 12, 2006   Views:0

Hi all,

When an event fires, say onmouseover='highlight_text();',
what is the object 'this' set to?

My problem is this, I'm dynamically creating a series of menu buttons based on data that is stored in a database. I want to change the .style of the buttons when the mouse hovers over them using the onmouseover and onmouseout events. Rather than create a new highlight() function for each menu item I want to use the same one for all of them. As far as I was aware, when a javascript event is fired, this points to the DOM object that initiated the event. However, this doesn't seem to be the case.

Can anyone help me out?

Jeff Gitter


Hi all,

I didn't find a reason as to why my this object was pointing to the wrong object but I found a suitable workaround in case anyone is interested.


/*in html file*/
<input type='button' ........ onmouseover='highlight_menu_opt(this.style)' />

function highlight_menu_opt(st)

It's kind of like cheating, but if my this object is pointing to some mysterious unknown (I'm guessing to my root <html> element or one of the <input>'s parent <div>'s because of referencing), I decided to pass it my element's style directly. Technically I'm still using the DOM, lol.

Hope this Helps some poor lost soul.


I know you figured your workaround but here is some explanation and suggestions.

"this" if not set is made as the window of the html.

It only refers to the DOM object when set by the object.


<input type="button value="Hi" onclick="alert(this.value)">

Yeah - if 'this' isn't set I realize it is set to the window object, but by playing with the object a little I determined that it wasn't in this instance. My guess is that it ended up being set to something else entirely due to referencing and it was giving me a headache trying to find out what. Thanks for your help anyway peej.


© 2018 2uzhan.com Contact