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.


​<div id="div-one">

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

My JS:

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


Answer by Didier Ghys

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

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


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
  property1: value1,
  property2: value2,


Use this

$("#div-one td").mouseover(function() {
}).mouseout(function() {

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");


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!