Jings
Jings

Reputation: 8690

jQuery hover function doesn't work for all div's

i am from Germany so be patient with my english :D

i take care of the hover function in jQuery to change the background color of some divs on my Page. The problem is not every div acts 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 absolute okay. But the seconds div's do nothing when i hover over it. What is going wrong :D

Thanks!

Upvotes: 4

Views: 1976

Answers (3)

karim79
karim79

Reputation: 342635

That is because you are duplicating the IDs of your divs. IDs, by definition, are supposed to be unique. Try assigning each div a class of 'book' and binding hover like so:

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

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

Relevant excerpt:

id = name [CS]

This attribute assigns a name to an element. This name must be unique in a document.

Upvotes: 4

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

You are using #book to assign the hover.

But id's are supposed to be unique and jQuery takes this into consideration, so it only applies the event handler to the first element with id book.

Use classes instead.

Upvotes: 3

FatherStorm
FatherStorm

Reputation: 7183

you need to reference multiple DIV's with either different ID's (which are supposed to be unique on the page) or by class. so change your <DIV id='book' to <DIV class='book' and $('#book') to $('.book')

Upvotes: 0

Related Questions