softpyramids
softpyramids

Reputation: 21

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 - http://sharifabraham.com/projects/

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?

Upvotes: 1

Views: 5263

Answers (2)

kapa
kapa

Reputation: 78691

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.

Upvotes: 1

Khez
Khez

Reputation: 10350

Hmz considering I understood corectly you want this:

HTML

<ul id="nav">
    <li><h3><a href="ideas.html">IDEAS</a></h3></li>
    <li><h3><a href="projects.html">PROJECTS</a></h3></li>
    <li><h3><a href="studio.html">STUDIO</a></h3></li>
</ul>

JS

$("#nav").hover(function(){$('#slider').hide();}, function(){$('#slider').show()});

Upvotes: 0

Related Questions