Tim Aych
Tim Aych

Reputation: 1365

JQuery hover function not working properly

I have three images (ex. tab1.jpg) along with mouseover images (ex. tab1m.jpg) that I'm trying to reduce into a single JQuery hover function. Before I was using:

$('#tab1').hover(function(){
    $(this).attr("src", 'images/tab1m.jpg');
},
function(){
    $(this).attr("src", 'images/tab1.jpg');
});
$('#tab2').hover(function(){
    $(this).attr("src", 'images/tab2m.jpg');
},
function(){
    $(this).attr("src", 'images/tab2.jpg');
});
$('#tab3').hover(function(){
    $(this).attr("src", 'images/tab3m.jpg');
},
function(){
    $(this).attr("src", 'images/tab3.jpg');
});

which worked, but was unnecessarily long and verbose. So I tried changing it to:

$('.navimg').hover(function(){
    var tab = ($(this).attr('id')).substring(3,4);
    $(this).attr('src','images/tab'+tab+'m.jpg');
},
function(){
    $(this).attr('src','images/tab'+tab+'.jpg');
});

which hasn't been working--when I mouse over the image it changes successfully but does not revert back to the original (tab1.jpg/tab2/tab3) image. Can anyone tell me why this is happening? Thanks!

Upvotes: 2

Views: 1110

Answers (3)

Harag
Harag

Reputation: 1582

How about using some CSS ?

#tab1{background-image: url(/images/tab1m.jpg)}
#tab1.hover{background-image: url(/images/tab1.jpg)}
#tab2{background-image: url(/images/tab2m.jpg)}
#tab2.hover{background-image: url(/images/tab2.jpg)}
#tab3{background-image: url(/images/tab3m.jpg)}
#tab3.hover{background-image: url(/images/tab3.jpg)}

then your JQuery hover can be:

$('.canHover').hover(function(){
    $(this).addClass('hover');
},
function(){
    $(this).removeClass('hover');
});

then in each of your 'tabs' add the 'canHover' class

<div id="#tab1" class="canHover">Tab 1</div>
<div id="#tab2" class="canHover">Tab 2</div>
<div id="#tab3" class="canHover">Tab 3</div>

using the above CSS and the "canHover" selector you can add hover function to any element you want.

Upvotes: 2

Nettogrof
Nettogrof

Reputation: 2136

It doesn't revert to the original, becuase in your second function the variable tab is undefine.

you could add

var tab = ($(this).attr('id')).substring(3,4);

in your second function to solve the problem

Upvotes: 1

Didier Ghys
Didier Ghys

Reputation: 30676

These are two different functions with two different scopes. You cannot access a variable declared in one of them in the second.

Make your declaration var tab outside the hover() so it is accessible in both the inner functions:

var tab = '';

$('.navimg').hover(
    function(){
        tab = ($(this).attr('id')).substring(3,4);
        $(this).attr('src','images/tab'+tab+'m.jpg');
    },
    function(){
        $(this).attr('src','images/tab'+tab+'.jpg');
    }
);

Upvotes: 5

Related Questions