Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change the image inside the li a img when hover the entire li using jQuery?

Tags:

jquery

I am trying to change the image inside the anchors inside the list item (li a img) using this simple jquery script but only change the image if the mouse is hover it, but i need to change the image if hover the entire li.

$(".overview li a img").hover(
    function() { this.src = this.src.replace("_off", "_on"); },
    function() { this.src = this.src.replace("_on", "_off"); }
);
like image 343
Emilio Yero Avatar asked Jan 26 '26 16:01

Emilio Yero


1 Answers

Change your selector to target the li, then within the handlers find the img children and modify their sources:

$(".overview li").hover(
    function() {
        $(this).find("img")[0].src = $(this).find("img")[0].src.replace("_off", "_on");
    }, function() {
        $(this).find("img")[0].src = $(this).find("img")[0].src.replace("_on", "_off");
    });    
});

If you like, you can squeeze that behaviour into a single function argument to .hover (it is a bit less readable though):

$(".overview li").hover(function () {
    var img = $(this).find("img")[0];
    img.src = (img.src.indexOf("_off") > -1) ? 
        img.src.replace("_off", "_on") : img.src.replace("_on", "_off");
});
like image 107
karim79 Avatar answered Jan 29 '26 05:01

karim79