softpyramids softpyramids - 1 year ago 162
jQuery Question

hover on text link to change image

I'm working on a project and need to work out some simple jquery for a text rollover that changes the image in the div behind it.

see the idea here -

i would like the image to fade in on:hover and fade out when the mouse leaves. each link on the nav will show the first image of the project.

make sense?

is this possible with css even?

Answer Source

This is just an outline of what you could do. On hover, we create a new img that will hold the necessary image and append it to #slider. The new img needs absolute positioning to appear on top of the previous image (we need this for fading). When mouse leaves the link, we just remove the img.

Change your HTML like this (add the corresponding image's URL to a data- attribute):

<a class="hoverlink" data-img="../images/flinders_house.jpg" href="...

And some jQuery:

var $slider=$('#slider'); //we save the slider
var $defaultimage=$('img', $slider); //and the default image

//mouseenter for the link
$('#projects .hoverlink').hover(function () { 
  var filename=$(this).attr('data-img'); //we get the filename from data-img

  $('<img id="hoverimage" src="'+filename+'" alt="" />')
    .appendTo($slider).fadeIn(500); //append and fade in new image (#hoverimage)

  $defaultimage.fadeOut(500); //fade out default image
//mouseleave for the link
function () { 
  $('#hoverimage').fadeOut(500, function () { //fade out #hoverimage
    $(this).remove(); //when animation is done, remove it

  $defaultimage.fadeIn(500); //meanwhile fade in original image

Also we need some CSS changes:

/* #hoverimage needs to appear on top of default image */
#slider { position: relative; }
#hoverimage { position: absolute; top: 0; left: 0; z-index: 100; }

NOTE: I haven't taken into consideration the loading time for these quite big images, my code assumes they are already cached. You could either do some preloading, or only start the fading effects when the image has loaded (.load()). The latter is not reliable in Opera if I remember well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download