mikeriley131
mikeriley131

Reputation: 393

How can I add a link to an image that changes on hover via jQuery?

I have an image below a nav and the image changes depending on which nav item is hovered over. Here is the code:

$(document).ready(function() {
    $('.nav-item').mouseenter(function() {
      var img = $(this).attr('data-headerimg'); 
      $('img#header-img').attr('src', img);
    }).mouseleave(function() {
      var img = $(this).attr('data-headerimg');
      $('img#header-img').attr('src', img);
    });
});

I'd like the image to be a link to it's corresponding page, but I'm not sure how to do that via jQuery. Any help would be greatly appreciated.

Upvotes: 0

Views: 35

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206028

Why to send an image request and wait a server response with image data? (Some users find it very annoying) In order to preload your images You can simply create the needed tags and just swap display (with fade?) on item hover.

Let's say:

<ul id="list">
   <li>Football</li>
   <li>Barbara</li>
</ul>
<div id="images">
   <a href="foo.html"><img src="foo.jpg" alt="Foo"></a>
   <a href="bar.html"><img src="bar.jpg" alt="Bar"></a>
</div>

#images a {
    display:none;
    position:absolute;
    /* etc */
}

var $imgLink = $('#images a');
$('#list li').hover(function( e ) {
  $imgLink.stop().fadeTo(300, 0);
  if(e.type=="mouseenter") {
      $imgLink.eq( $(this).index() ).fadeTo(300, 1);
  }
});

Upvotes: 0

Amadan
Amadan

Reputation: 198324

First, enclose the image in an anchor in your HTML: <a><img ....></a>. Put the link next to data-headerimg, in data-headerlink attribute.

Second, update the anchor's href to the same value you're setting the image's src:

var img = $(this).attr('data-headerimg'); 
var href = $(this).attr('data-headerlink'); 
$('img#header-img').attr('src', img).parent().attr('href', href);

Upvotes: 1

Sesertin
Sesertin

Reputation: 462

Sorround it with a href tag in html like

<a id="headerimglink" href=""><img src="" /></a>

set the href attribute along with the src attribute, or you can hardcode it as well if that is not changing.

Upvotes: 0

Related Questions