Salvio
Salvio

Reputation: 100

Hover function in jQuery doesn't work

I have four li div that have inside a link of an image (so they're four links and four images), but I can't understand why the hover function doesn't work here .

The error is :

element.hover isn't a function:

var element =$("li div")
var element_link = element.find("a");
var element_img = element.find("img");
element_img.css("opacity","0.5");
element_link.each(function(index, element) {
    element.hover(
    function(){element_img[index].animate({opacity:1}),250},
    function(){element_img[index].animate({opacity:0.5}),250}
    );
});

How can I fix this problem?

Upvotes: 2

Views: 193

Answers (2)

Stephan Muller
Stephan Muller

Reputation: 27600

You don't need to use each() on a collection of jQuery elements. You can simply use the following code to apply the hover to all of the element_links:

element_link.hover(
  function(){$(this).siblings('img').animate({opacity:1}),250},
  function(){$(this).siblings('img').animate({opacity:0.5}),250}
);

Upvotes: 3

Salvio
Salvio

Reputation: 100

I solved in this way:

var element =$("li div");
var element_link = element.find("a");
var element_img = element.find("img");
element_img.css("opacity","0.5");

element_link.each(function(index, element) {
    $(element).hover(
   function(){$(element_img[index]).animate({opacity:1},250)},
   function(){$(element_img[index]).animate({opacity:0.5},250)}
);
});

Thank to Wolf and Amit too( there were an error in animate function too).

Upvotes: 3

Related Questions