What's the correct way to change an image on mouseover and back on mouseout (with/without jQuery)?
<a href="#" id="name">
<img title="Hello" src="/ico/view.png" onmouseover="$(this).attr('src','/ico/view.hover.png')" />
</a>
Ok, this is working, but how to change back to the original image after mouseout
?
If it is possible, I want to do this thing inline, without document.ready function.
Answer: Use the CSS background-image property You can simply use the CSS background-image property in combination with the :hover pseudo-class to replace or change the image on mouseover.
The onmouseover attribute fires when the mouse pointer moves over an element. Tip: The onmouseover attribute is often used together with the onmouseout attribute.
Definition and UsageThe onmouseover event occurs when the mouse pointer is moved onto an element, or onto one of its children. Tip: This event is often used together with the onmouseout event, which occurs when a user moves the mouse pointer out of an element.
A mouseover is an event that occurs in a Graphical User Interface (GUI) when the mouse pointer is moved over an object on the screen such as an icon, a button, text box, or even the edge of a window.
here's a native javascript inline code to change image onmouseover & onmouseout:
<a href="#" id="name">
<img title="Hello" src="/ico/view.png" onmouseover="this.src='/ico/view.hover.png'" onmouseout="this.src='/ico/view.png'" />
</a>
Try something like this:
HTML:
<img src='/folder/image1.jpg' id='imageid'/>
jQuery:
$('#imageid').hover(function() {
$(this).attr('src', '/folder/image2.jpg');
}, function() {
$(this).attr('src', '/folder/image1.jpg');
});
EDIT: (After OP HTML posted)
HTML:
<a href="#" id="name">
<img title="Hello" src="/ico/view.png"/>
</a>
jQuery:
$('#name img').hover(function() {
$(this).attr('src', '/ico/view1.png');
}, function() {
$(this).attr('src', '/ico/view.png');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With