Reputation: 263
I am currently having some problems getting a mouseover and mouseout function to work in jquery. I have two images called 'images/doomsday.jpg' and the other called 'keep_calm.png' which i want to swap when the mouse is over them and then swap back when it is not. I have included the code I am currently trying to use, can anybody see any problems with it and where I am going wrong?
$(function() {
$("images/doomsday.jpg")
.mouseover(function() {
var src = $(this).attr("src").match(/[^\.]+/) + "images/keep_calm.png";
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src").replace("images/keep_calm.png");
$(this).attr("src", src);
});
});
Upvotes: 2
Views: 14413
Reputation: 307
There were no selectors used. Here's how your final code should look like
The HTML
<div> <img src="images/doomsday.jpg" id='myimage' /> </div>
The Javascript
$('document').ready(function() {
$(function() {
$("#myimage")
.mouseover(function() {
var src = $(this).attr("src").match(/[^\.]+/) + "images/keep_calm.png";
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src").replace("images/keep_calm.png");
$(this).attr("src", src);
});
});
});
Upvotes: 1
Reputation: 1169
maybe something like this DEMO: http://jsfiddle.net/m4WuU/ just use Jquery toggleClass
HTML
<div class="holder"><div>
CSS:
.holder {
background-image:url('images/keep_calm.png');
}
.swapHolder {
background-image:url('images/doomsday.png');
}
JS:
$('.holder').on('hover', function () {
$('.holder').toggleClass('swapHolder');
});
Upvotes: 1
Reputation: 8477
Your selectors are wrong. You can learn about the selectors here.
Here is a demo of image swapping.
Code :
$('document').ready(function() {
$('img').on({
'mouseover' : function() {
$(this).attr('src','http://media02.hongkiat.com/css3-code-slim/css3-markup.jpg');
},
mouseout : function() {
$(this).attr('src','http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png');
}
});
});
Upvotes: 7
Reputation: 33272
Apparently the selector is wrong:
You should use for example $("#imageid")
where image id is the id of the image you want to change.
Upvotes: 0