onmouseover and inline function using the 'this' object

15,541

Solution 1

I don't know if you want to be using an anonymous function there. I think

<div id="some_div" style="border: solid 1px red; width:50px; height: 50px;" 
onmouseover="$(this).css('background','green');"></div>

will work.

Solution 2

If you really need to wrap it up in an anonymous function, you can do this.

onmouseover="(function(that){$(that).css('background','green');})(this);"

Solution 3

@matt you can do the same with css, just by using the :hover on the class.

.SomeDiv
{
    border: solid 1px red; 
    width:50px; 
    height: 50px;
    /*remove the below line if you like to keep the hover color*/
    background-color:white;
}

.SomeDiv:hover
{
    background-color:green;
}

and

<div id="some_div" class="SomeDiv"></div>

Solution 4

This is going to be messed up because you're executing the function. Let's break this up a little.

If this was not inline, it would look like this:

onmouseover = (function(){
    $(this).css('background','green');
})();

Notice the () at the end? This means you're executing the code before the function gets assigned to onmouseover.

Try this instead:

<div id="some_div" style="border: solid 1px red; width:50px; height: 50px;" onmouseover="$(this).css('background','green');"></div>

Solution 5

Seems you're using jQuery, why not do it all the way

$('#tag').hover(function() { $(this).css('background', 'green'); });
<div id="tag"> ... </div>
Share:
15,541
Matt
Author by

Matt

Hello

Updated on June 08, 2022

Comments

  • Matt
    Matt almost 2 years

    I have the following bit of code:

    <div id="some_div" style="border: solid 1px red; width:50px; height: 50px;" 
    onmouseover="(function(){$(this).css('background','green');})();"></div>
    

    The function gets run just fine but it doesn't seem to be able to find the 'this'. How can I make it so that it will know to self-reference?

    (Yes, jquery is referenced in my code)

  • Dogbert
    Dogbert almost 13 years
    he probably doesn't want to remove the background on mouseout. (Atleast from his code snippet).
  • Aristos
    Aristos almost 13 years
    @Dogbert this is easy, you do not use the background-color on the .SomveDiv, only on hover.
  • Dogbert
    Dogbert almost 13 years
    if I hover in and out using your code, the green will go away. But op's original code will stay green.
  • Aristos
    Aristos almost 13 years
    @Dogbert remove one line as I comment on code, and the green will stay