I'm looking to swap an img src on hover. Typically I would use:
$('#img').hover(function() {
$(this).attr('src', 'http://www.example.com/new-img.jpg');
});
However, I'm loading the content in via Ajax so normally I would use:
$('#main').on('hover', '#img', function() {
$('#img').attr('src', 'http://www.example.com/new-img.jpg');
});
But I'm reading that on('hover', ...) was deprecated in jQuery 1.8 and removed in 1.9 (jQuery Docs), which is what I'm currently using. Do anyone have any work arounds other than using:
$('#main').on('mouseenter', '#img', function() {
$('#img').attr('src', 'http://www.example.com/new-img.jpg');
});
$('#main').on('mouseleave', '#img', function() {
$('#img').attr('src', 'http://www.example.com/old-img.jpg');
});
No, you'll need to do it in two calls. But for added jQuery points, you can chain them:
And as Benjamin comments below, you can optimise further (you get plain old Javascript points this time):
You can apply multiple events and then check
event.type
like this:jsFiddle
You can also use
switch-case
orif/else
:Here is an alternative approach that involves no JavaScript at all:
Instead of using an
<img>
with asrc
attribute use a div, give that div the same id (remember to give it the right width and height).In your css, give that
div
abackground-image
something like:On
:hover
change it(fiddle)