February 28, 2012

jquery – leaving the hover state

Question by Marc

I have 2 div tag. The first contains a table. The second contains some text. When the page is loaded both div have no background-color. When there is an hover on a td of the first div, the second div background-color is set to yellow (see code below). My problem is that when I leave the table with the mouse, the background of the second div stays yellow. I would like the color to be remove on leaving the hover state. Hope someone can help. Thank you in advance for your replies. Cheers. Marc.

My HTML :

​<div id="div-one">
    <table>
        <tr><td>1</td><td>2</td></tr>
        <tr><td>3</td><td>4</td></tr>
        <tr><td>5</td><td>6</td></tr>
        <tr><td>7</td><td>8</td></tr>                   
    </table>
</div>

​<div id="div-two">
    some text
</div>

My JS:

$(document).on("hover", "#div-one td", function() { 

    $("#div-two").css("background-color":"yellow");
});​

Answer by Didier Ghys

Use mouseenter and mouseleave events separately – which is actually a “hover” event:

$(document).on({
    mouseenter: function() {
        $("#div-two").css("background-color", "yellow");
    },
    mouseleave: function() {
        $("#div-two").css("background-color", "");
    }
}, "#div-one td");​

DEMO

Answer by Starx

There is an error, you are using : when defining single property.
When defining a single property you should use ,

// For single property
$("#selector").css("property", "value");

//Define multiple properties
$("#anotherselector").css({
  property1: value1,
  property2: value2,
});

Solution

Use this

$("#div-one td").mouseover(function() {
    $("#div-two").css("background-color","yellow");
}).mouseout(function() {
    $("#div-two").css("background-color","white");
});

Or, if you want to keep on using .on() method

$(document).on("hover", "#div-one td", function() {
    $("#div-two").css("background-color", "yellow");
}).on("mouseout", "#div-one td", function() {
    $("#div-two").css("background-color", "white");
});

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!