0

I'm trying to work out why my code isn't working here, any debugging would be helpful. Basically the purpose is to change the img contained within ".col" on mouseenter and back to the original on mouseleave. I also want to pre-load the images so there is no delay upon the mouseenter event.

Example of single Gallery Item HTML

<div class="col span_1_of_3 span_1_of_2" id="challenger">
    <a href="projects/challenge.html">
        <div class="projectImage">
        <div class="hovtext">Challenger</div>
            <img src="img/8.png" data-hover="img/8h.png"/>
        </div>
        <span class="title">Challenger</span>
        <span class="viewpr">View Project</span>
    </a>
</div>

JQuery

$(function () {
    $('.col').each(function () {
          var $img = $(this).find('img');
          $img.data('original', $img.attr('src'));
          var img = new Image();
          img.src = $img.data('hover');
    }).mouseenter(function () {
          $(this).find('img').attr('src', $(this).data('hover'));
    }).mouseleave(function () {
          $(this).find('img').attr('src', $(this).data('original'));
    })
})

Any questions please go ahead and ask.

Edit - website in question is here: www.williamrenwick.co.uk

Thanks, Will

  • For pre-loading images :http://stackoverflow.com/questions/476679/preloading-images-with-jquery Your closing div tag isn't fully formed, but that shouldn't cause your issue. – Jay Blanchard Apr 30 '14 at 13:09
  • a question: you need the img tag? or you can use a div and insert the image as a background? for the second option there is a very easy solution with only css – Emanuele Parisio Apr 30 '14 at 13:27
  • Yeah I've been thinking about using css background property, but essentially I want to keep it like this as I've devised a responsive grid system around it and I don't want to go back to square one unless completely necessary. – user3586963 Apr 30 '14 at 13:30

1 Answers1

1

In your original code the $(this) in the image source is not what you think -

$(this).find('img').attr('src', $(this).data('hover')); //second $(this) is still the column, not the image

Here is a less convoluted solution -

$('.col').mouseenter(function () {
    var hover = $(this).find('img').data('hover');
    var original = $(this).find('img').attr('src');
    $(this).find('img').attr('data-original', original);
    $(this).find('img').attr('src', hover);
}).mouseleave(function () {
    var original = $(this).find('img').data('original');
    $(this).find('img').attr('src', original);
});

You can see it at work here - http://jsfiddle.net/jayblanchard/au7a6/

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119