Hasem Uddin
Hasem Uddin

Reputation: 19

Jquery hover selection not working

I have a gallery that contains 10 images with same class. I want to use hover effect for each image separately using jquery and css3. I have used a way to select images and apply animation. But If i hover over one image, I have seen that animation effect is applied to all images.

My main DIV id name #continer and all images id #image_id

$("#image_id").hover(function () {
    $("#image_id").addClass("start_animation")
});

Upvotes: 0

Views: 29

Answers (3)

DevlshOne
DevlshOne

Reputation: 8457

The right way to do this:

$("#container").hover(function (e) {
 $(e.target).addClass("start_animation")
});

Upvotes: 0

Vikash
Vikash

Reputation: 714

$("#image_id").hover(function () {
 $(this).addClass("start_animation")
});

Try above code.

Upvotes: 0

Tim Vermaelen
Tim Vermaelen

Reputation: 7069

The problem is an id has to be unique. Instead you need to select the classname for each image. Or you can use the parent and select the img tag from there:

$('#container').on('mousein', 'img', function(){
    $(this).addClass('start_animation');
});

In the above example I've used an event delegation mouseover on the #container and it will automatically apply this event to the img selector.

Now typically the hover() function takes 2 function parameters for the mousein/mouseout event. So to get rid of the class after mouseout you'll have to bind that event as well.

$('#container').on('mouseout', 'img', function(){
    $(this).removeClass('start_animation');
});

Upvotes: 1

Related Questions