Simple Javascript for image mouseovers

Date: 17th January 2008 at 12:54 am | Filed under: development, scripts | Author: Sam Burdge

This is a simple javascript for creating a mouseover effect on image links, also known as an image replacement script. It works in two stages. In this example "image 1" is the link image and "image 2" is the mouseover image.

Stage 1

Add this javascript to the head of your page:

function SwapImage1() {
document.image1.src="/images/image2.jpg"
}
 
function SwapImage1Back() {
document.image1.src="/img/image1.jpg"
}

Stage 2

Add the following onmouseover and onmouseout properties to your image:

<img src="/images/image1.jpg"
onmouseout="SwapImage1Back()" onmouseover="SwapImage1()" name="image1" />

3 Responses to “Simple Javascript for image mouseovers”

  • Comment by Donna Newby
    Date: July 17th, 2009 at 10:43 am

    Hi Sam,
    Thanks for the the helpful tips, i was wondering if you could help me over come a small challenge i am experiencing with adding this script to my WP blog, i want to add it two a java script widget in the side bar, if this is the case where do I paste the first part of the script? I have tried to put booth codes in the widget and it works great, but when I go to add another in the same or another widget the mouseover effect dosen’t happen? im stuck, here is n exmple of wht i m trying to chieve http://ruslantesliavych.com kinda like a picture menue bar. any help or direction would be truly appricited, thank you kindly. Donna

  • Comment by Sam Burdge
    Date: July 17th, 2009 at 11:04 am

    Hi Donna

    You might find this tutorial is a better alternative for what you are trying to do:
    http://www.samburdge.co.uk/development/image-mouseovers-without-javascript-css-sprites

    It is a way of doing the same thing, but just with CSS, no need for javascript.

    To do more than one image using the javascript above:

    in the head of the page:

    <script type=”text/javascript”>
    function SwapImage1() {
    document.image1.src=”/images/image2.jpg”
    }

    function SwapImage1Back() {
    document.image1.src=”/img/image1.jpg”
    }

    function SwapImage2() {
    document.image2.src=”/images/image4.jpg”
    }

    function SwapImage2Back() {
    document.image2.src=”/img/image3.jpg”
    }
    </script>

    in the body of the page:

    <img src=”/images/image1.jpg”
    onmouseout=”SwapImage1Back()” onmouseover=”SwapImage1()” name=”image1″ />

    <img src=”/images/image3.jpg”
    onmouseout=”SwapImage2Back()” onmouseover=”SwapImage2()” name=”image2″ />

  • Comment by Sam Burdge
    Date: July 17th, 2009 at 11:11 am

    You can see an example of this script working on multiple images at: http://www.pinkyvision.com

Leave a Comment