jsg
jsg

Reputation: 1264

Having multiple image with same hover over effects

So i currently have multiple images on a page, however when i want over hover effect on the one that is being hovered over. Where the page has more than 12 images, one way is to replicate this code 12 times, with an id but is there a more efficient way:

$("img").hover(function () {
    $("img").addClass("transition");
}, function () {
    $("img").removeClass("transition");
});

Upvotes: 0

Views: 856

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

You could use in/out hover handler to toggle the class:

$("img").hover(function () {
    $(this).toggleClass("transition");
});

But be aware, this could be done using only CSS with pseudo class :hover if your goal is just to apply transition to these images.

Upvotes: 5

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

In order to apply hover effect only on currently hovered image and not on the other images, use $(this) as shown below :-

$("img").hover(function () {
    $(this).addClass("transition");
}, function () {
    $(this).removeClass("transition");
});

Upvotes: 4

Related Questions