Search code examples
jqueryimagenavigationswap

Nav button hover will swap respective images


I'm having a tough time wrapping my head around this one.

nav concept

Hovering a navbar button will change the image for its respective "spotlight", the one directly below it.

I've been trying many different approaches, and as I'm still far from memorizing the full range of jQuery's functions, I just can't grasp this one.

So far, this is the best one, but it requires me to assign an ID to every element, and I haven't been able to figure out how to get a nice crossfade going.

$('a#nav2').hover(function() {
    $('#nav2_light').attr("src","../img/nav/light_bright.png");
}, function() {
    $('#nav2_light').attr("src","../img/nav/light.png");
});

I'm trying to find: 1. A more efficient method of accomplishing this for each nav button and its respective spotlight 2. A way to crossfade the images. fadeOut and fadeIn completely fade the picture out before fading the next one in, which isn't what I'm looking for.

I understand questions similar to this have been asked, but the ones I've found have all been instances with only one image. I'd like to make the function repeatable for each menu item. Ideas? Thank you in advance for your help!

Edit: Just to clarify, the nav buttons and spotlights are separate entities. I'm not sure if $this will work in this case. In the illustration, I have the nav buttons all in one div, and the spotlights in a different one.

Edit 2: I've toyed with it a bit and I suppose it works if I just assign an ID for each. However, I am still looking for a way to make the swap do a crossfade. Anyone know how to do this if I'm using the .attr function?


Solution

  • use class for each elements you want to add this function and

    $('.class_name').hover(function() {     
    $(this).attr("src","../img/nav/light_bright.png");         
    }, function() {  
       $(this).attr("src","../img/nav/light.png"); 
    });