Question

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

Was it helpful?

Solution

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/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top