JQuery hover function not working for all divs

I am from Germany, so be patient with my English: D

I will take care of the hover function in jQuery to change the background color of some divs on my page. The problem is not with every div when I hover over it.

$(document).ready(function(){ $('#book').hover(function(){ $(this).css('background', '#dfdfdf'); }, function(){ $(this).css('background', '#eee'); }); }); 

The first div on my page is absolutely right. But the seconds of the div do nothing when I hover over it. What is going wrong: D

Thanks!

+4
source share
3 answers

You use #book to assign a hang.

But id must be unique, and jQuery takes this into account, so it only applies the event handler to the first element with the id book.

Use classes instead.

+3
source

This is because you are duplicating the identifiers of your divs. Identifiers, by definition, must be unique. Try assigning a “book” class to each div and binding the hover as follows:

 $('.book').hover(function(){... 

See specification: http://www.w3.org/TR/html4/struct/global.html#h-7.5.2

Appropriate exposure:

id = name [CS]

This attribute names the element. This name must be unique in the document.

+4
source

you need to reference multiple DIVs with any other identifier (which must be unique on the page) or by class. so change <DIV id='book' to <DIV class='book' and $('#book') to $('.book')

0
source

All Articles