Change Image on Mouse hover using jQuery

Leave a Comment

A rollover image is just an image swap triggered by the mouse moving over an image. In other words, you simply assign the image swap to the mouseover event.

For example, say you have an image on the page with an ID of photo. When the mouse rolls over that image, you want the new image to appear. You can accomplish that with jQuery like this:
<script src="jquery-1.6.3.min.js"></script>
<script >
$(document).ready(function () {
    var newPhoto = new Image();
    newPhoto.src = 'images/newImage.jpg';
    $('#photo').mouseover(function () {
        $(this).attr('src', newPhoto.src);
    }); // end mouseover
}); // end ready
</script>

Note : You need to also add a mouseout event to swap back the image.

jQuery provides its own event, called hover(), which takes care of both the mouseover and mouseout events:

<script src="jquery-1.6.3.min.js"></script>
<script>
$(document).ready(function () {
    var newPhoto = new Image();
    newPhoto.src = 'images/newImage.jpg';
    var oldSrc = $('#photo').attr('src');
    $('#photo').hover(
function () {
    $(this).attr('src', newPhoto.src);
},
function () {
    $(this).attr('src', oldSrc);
}); // end hover
}); // end ready
</script>


0 comments:

Post a Comment