How To Add Cool Javascript Rollover Effects To Images

javascript rolloversJavascript image rollovers are used to bring interactivity to webpages. The use of the rollover is one of the most popular forms of Javascript on the web. Javascript rollovers (or mouse-over effects) are fairly common on today’s websites and can be used very creatively.

You’ve seen them. Images that have been constructed this way change when you drag your mouse over them and change back when you remove the cursor. Mouse-over effects are very easy to create and they can really add life to your images or website.

In this article I’m going to show you how to add cool Javascript rollover effects to images on your website.


Have no idea what I’m talking about? If you want to become more familiar with Javascript, I invite you to check out the article Varun composed last week entitled What is JavaScript and How Does It Work?. Also, you can Quickly Check If You’re Running A JavaScript Enabled Browser.

Now that you’re feeling a little more confident we can begin.

Step 1: Create Two Images

In order for this effect to work properly, you need to create two images. Ideally, these should have the same dimensions (height and width) and should reside in the same directory. It’s important that you can remember and differentiate between the names of the images, so don’t name them anything too long or difficult.

javascript rollovers

For this example I have named my images testbox1.gif and testbox2.gif.

Step 2: Create An HTML Document

After creating the images, it’s time to create the code. In Notepad, start typing up a simple HTML file.  We will insert our Javascript after the <head> tag.

javascript rollovers

All we are doing here is defining the images. Although my code has testbox1 and testbox2 you can change these to the names of your two images.

The <body> tag is where we’ll insert our call to action. Within the <body> tag, insert the image source code the way you would any other HTML image, except in this case we have to add the mouseover and mouseout functions to the code to achieve the rollover effect.

javascript image rollovers

When finished, save the file as a ‘.html’ file. You can double click the file and it should open up in your web browser with your images and rollover effect working properly. Now that you’ve tested your code you can add it to your website and begin amazing people with your flashy Javascript.

To see it in action, click here and mouse over the image to see what we have just created.

Conclusion

This code should be all you will need to utilize any rollovers you want on the webpage. The ‘over’ and ‘out’ functions are what will be doing all the work here. They call the images when the mouse is moved over them and off of them.

For the image source, you only need to type the name of the image, so long as the HTML file is saved in the same folder the images are. If they are not, you need only to point to the images’ location like you would any other image in HTML.

Was this article helpful for you? Will you be utilizing JavaScript rollovers on your website? I would love to hear your thoughts and ideas in the comment section below!

Image Credit: Noah Sussman

Tagged:

Steve Campbell

Steve, a Community Manager at VaynerMedia, is passionate about social media and brand building. Follow him on Twitter @Steve_Campbell & his Social Branding Blog.

Similar Stuff

The comments were closed because the article is more than 90 days old.

If you have any questions related to stuff mentioned in the article or need help with any computer issue, just ask it on MakeUseOf Answers.

  • http://blog.stephenli.ca Stephen

    Why use javascript to accomplish something that CSS can do?

    • http://www.socialbrandingblog.com/ Steve Campbell

      Good point, Stephen. I chose to write the article on javascript because more
      people have searched for that method online which creates added SEO
      benefits. The CSS method is just as easy, and I might do something with CSS
      in the near future.

      • http://pceasies.com pceasies

        This has long been a feature in Dreamweaver although Dreamweaver likes to use a lot of code for simple features.

        Here’s the CSS way using sprites: http://www.webvamp.co.uk/blog/coding/css-image-rollovers/

      • http://pceasies.com pceasies

        I’d recommend adding the benefits and details of the CSS way before the whole interwebs decides to condemn you.

        • http://www.socialbrandingblog.com/ Steve Campbell

          You’re right. I’ll see what I can do.

  • Stephen

    Why use javascript to accomplish something that CSS can do?

  • Steve Campbell

    Good point, Stephen. I chose to write the article on javascript because more
    people have searched for that method online which creates added SEO
    benefits. The CSS method is just as easy, and I might do something with CSS
    in the near future.

  • Rob

    Wow, is it 1994 again? Embedding script in HTML tags? Using script where CSS would do the job?

    Very disappointed in MUO for perpetuating such bad practice and outdated techniques.

    • http://www.socialbrandingblog.com/ Steve Campbell

      Very sorry, Rob. Just typed up an article for anyone who wanted to know how to do it this way. I should have added the CSS benefits in.

  • Rob

    Wow, is it 1994 again? Embedding script in HTML tags? Using script where CSS would do the job?

    Very disappointed in MUO for perpetuating such bad practice and outdated techniques.

  • pceasies

    This has long been a feature in Dreamweaver although Dreamweaver likes to use a lot of code for simple features.

    Here’s the CSS way using sprites: http://www.webvamp.co.uk/blog/…

  • pceasies

    I’d recommend adding the benefits and details of the CSS way before the whole interwebs decides to condemn you.

  • Steve Campbell

    You’re right. I’ll see what I can do.

  • Steve Campbell

    Very sorry, Rob. Just typed up an article for anyone who wanted to know how to do it this way. I should have added the CSS benefits in.

  • http://twitter.com/rwaldron rick waldron

    “Just typed up an article for anyone who wanted to know how to do it this way”

    This perpetuates bad practice and is extraordinarily irresponsible. It’s also a slap in the face to many developers who sow best practices. In this one article you’ve condoned:

    1. DOCTYPE omission
    2. Assignment without `var`
    3. Implied globals
    4. Omission of any load event handler
    5. Omission of semi-colons
    6. Omission of parens on an invoking constructor
    7. Inline event handlers

    This is just shameful.

    • http://www.socialbrandingblog.com/ Steve Campbell

      Apologies, Rick. I realize I screwed up. I’m not a developer by any stretch.

      • http://jdclayton.com Josh Clayton

        Steve, if you’re not a developer, why would you write a technical post in the first place? If you know any developers that write HTML and Javascript, I’d present your idea to one of them and ask them to draft something instead. It’d be one thing if your posts were never read, but I’m guessing this site gets some traffic and will end up doing more harm than good.

        Another option would be to ask the editor (or whoever handles post management) to remove this article so that people getting into HTML and Javascript don’t start learning “the wrong way.”

        • http://www.socialbrandingblog.com/ Steve Campbell

          Better yet, if one of you wants to email me the proper code I will have it
          placed in the article. My MUO email is stevencampbell@makeuseof.com

          • http://jdclayton.com Josh Clayton

            Steve, the entire article should be rewritten to use CSS instead of Javascript for changing images with the :hover pseudo-selector. Using Javascript for handling image rollovers, while it can be done, shouldn’t be done. This article is the equivalent of suggesting using font tags to style a website.

          • http://www.socialbrandingblog.com/ Steve Campbell

            In that case I’ll see what I can do. If the title I selected had said CSS I
            would have written it that way, but the list we select from just had one for
            javascript rollovers, so I wrote it. I got the code to do what I wanted,
            just didn’t realize I would offend all the developers reading the blog :) Oh
            well, you live and you learn right?

          • http://pceasies.com pceasies

            Yep, never good enough for the professional developers.

          • http://twitter.com/truthvalue Andrew

            No mister, you are misguiding your readers, article is utterly useless. Please remove it.

    • http://mathiasbynens.be/ Mathias

      Not to mention — seriously?

      • http://pceasies.com pceasies

        I think he may have been confused and put language instead of type. Type is required for the HTML attribute

    • http://twitter.com/truthvalue Andrew

      He’s probably crying in the corner by now.

      • http://www.socialbrandingblog.com/ Steve Campbell

        lol nope, I think I’ll be fine.

  • rick waldron

    “Just typed up an article for anyone who wanted to know how to do it this way”

    This perpetuates bad practice and is extraordinarily irresponsible. It’s also a slap in the face to many developers who sow best practices. In this one article you’ve condoned:

    1. DOCTYPE omission
    2. Assignment without `var`
    3. Implied globals
    4. Omission of any load event handler
    5. Omission of semi-colons
    6. Omission of parens on an invoking constructor
    7. Inline event handlers

    This is just shameful.

  • Steve Campbell

    Apologies, Rick. I realize I screwed up. I’m not a developer by any stretch.

  • Josh Clayton

    Steve, if you’re not a developer, why would you write a technical post in the first place? If you know any developers that write HTML and Javascript, I’d present your idea to one of them and ask them to draft something instead. It’d be one thing if your posts were never read, but I’m guessing this site gets some traffic and will end up doing more harm than good.

    Another option would be to ask the editor (or whoever handles post management) to remove this article so that people getting into HTML and Javascript don’t start learning “the wrong way.”

  • Steve Campbell

    Better yet, if one of you wants to email me the proper code I will have it
    placed in the article. My MUO email is stevencampbell@makeuseof.com

  • Josh Clayton

    Steve, the entire article should be rewritten to use CSS instead of Javascript for changing images with the :hover pseudo-selector. Using Javascript for handling image rollovers, while it can be done, shouldn’t be done. This article is the equivalent of suggesting using font tags to style a website.

  • Steve Campbell

    In that case I’ll see what I can do. If the title I selected had said CSS I
    would have written it that way, but the list we select from just had one for
    javascript rollovers, so I wrote it. I got the code to do what I wanted,
    just didn’t realize I would offend all the developers reading the blog :) Oh
    well, you live and you learn right?

  • pceasies

    Yep, never good enough for the professional developers.

  • Lucanos

    Is is April Fools Day? Have I slipped through some kind of wormhole and arrived back in the early 90′s?

    Whilst this is a method which could be used (and was, extensively, 10-20 years ago), the more modern use of CSS to perform this action, and the use of Sprites to reduce the number of images being loaded (ie having Image1 and Image2 actually be the same file, but with one above the other, allowing for an easy transition by changing the background position in CSS) are far faster and simpler.

    Considering some of the other feedback being left here, I would suggest changing this article into one which details “How we did it, and How we do it now” piece, thereby answering the questions about how to achieve this kind of functionality (should anyone want it), but also illustrating the other options for doing the same and the pros/cons of each.

    PS – When declaring the images for use, you do not have to actually make them through “new Image”, as the only part of that object you are using is the “.src” property, which is a string. You could have just as easily had ‘var textbox1 = “textbox1.gif”; var textbox2 = “textbox2.gif”;’

    • http://www.socialbrandingblog.com/ Steve Campbell

      That is a brilliant idea. Thanks Lucanos!

  • Lucanos

    Is is April Fools Day? Have I slipped through some kind of wormhole and arrived back in the early 90′s?

    Whilst this is a method which could be used (and was, extensively, 10-20 years ago), the more modern use of CSS to perform this action, and the use of Sprites to reduce the number of images being loaded (ie having Image1 and Image2 actually be the same file, but with one above the other, allowing for an easy transition by changing the background position in CSS) are far faster and simpler.

    Considering some of the other feedback being left here, I would suggest changing this article into one which details “How we did it, and How we do it now” piece, thereby answering the questions about how to achieve this kind of functionality (should anyone want it), but also illustrating the other options for doing the same and the pros/cons of each.

    PS – When declaring the images for use, you do not have to actually make them through “new Image”, as the only part of that object you are using is the “.src” property, which is a string. You could have just as easily had ‘var textbox1 = “textbox1.gif”; var textbox2 = “textbox2.gif”;’

  • Steve Campbell

    That is a brilliant idea. Thanks Lucanos!

  • Mathias

    Not to mention <script language=”JavaScript”> — seriously?</script>

  • http://www.facebook.com/adam.j.sontag adam j. sontag

    There’s no point in fixing this post to have better techniques. The web would simply be better off without it.

  • adam j. sontag

    There’s no point in fixing this post to have better techniques. The web would simply be better off without it.

  • http://thedailybuggle.com ænon1mus

    Hi guys,

    Thanks for your input but Steve was writing a highly sought for article. While CSS is replacing Javascript in webdesign, it’s still being searched for on a daily basis.

    • http://www.facebook.com/adam.j.sontag adam j. sontag

      Perhaps you guys should focus more on improving the ecosystem of the web than making fractions of cents by squeezing as much SEO-juice as you can out of outrageously bad and outdated practises.

      • http://www.socialbrandingblog.com/ Steve Campbell

        adam j. sontag,

        Since you are clearly very passionate about this subject (and this goes to the rest of you as well), why not consider helping the site by becoming a writer? Contributors are only required to write 3 articles a month and I think we could all use some well-written technical articles by top web developers.

  • ænon1mus

    Hi guys,

    Thanks for your input but Steve was writing a highly sought for article. While CSS is replacing Javascript in webdesign, it’s still being searched for on a daily basis.

  • Andrew

    He’s probably crying in the corner by now.

  • Andrew

    No mister, you are misguiding your readers, article is utterly useless. Please remove it.

  • adam j. sontag

    Perhaps you guys should focus more on improving the ecosystem of the web than making fractions of cents by squeezing as much SEO-juice as you can out of outrageously bad and outdated practises.

  • Coaldead

    Really liked your article, thanks for the tips. Don’t worry, haters gonna hate.

    • http://www.socialbrandingblog.com/ Steve Campbell

      Thanks, Coaldead, although I do agree with the readers’ opinions and am looking into remedying this situation. I will attempt to write an article on CSS image rollovers for next week. Anyone want to help?

      • Anonymous

        Do actual research this time and don’t copy and paste the first CSS tutorial you find on Google. The fact that people might actually take your advice in this article – like Coaldead – makes me want to vomit.

        You guys definitely underestimate the value of thoughtful, authoritative articles. Instead of writing the shittest “tutorials” to spam the word JavaScript, while completely decrediting yourselves in the process, try writing something that people will want to share, bookmark, and keep coming back to.

        • Rob

          Agreed. This was a shameless traffic grab. Very disappointed in MUO for this one.

          • http://www.socialbrandingblog.com/ Steve Campbell

            I disagree as well. Most of the articles written are based on SEO research.
            Just because this one was based on an out-dated practice was only the fault
            of that research and a misunderstanding, don’t think it was a deliberate
            attempt to score traffic.

        • http://www.socialbrandingblog.com/ Steve Campbell

          I couldn’t disagree with you more. I’m afraid you’ve mistaken my lack of
          programming knowledge for laziness. I assure you I do research all of my
          articles beforehand with the intent of putting out quality work. I’ve
          written nearly 50 articles now for MUO and this is the first bad one I’ve
          come up with. Don’t think I’ve purposely come up with a dud here.

  • Coaldead

    Really liked your article, thanks for the tips. Don’t worry, haters gonna hate.

  • Steve Campbell

    lol nope, I think I’ll be fine.

  • Steve Campbell

    Thanks, Coaldead, although I do agree with the readers’ opinions and am looking into remedying this situation. I will attempt to write an article on CSS image rollovers for next week. Anyone want to help?

  • Steve Campbell

    adam j. sontag,

    Since you are clearly very passionate about this subject (and this goes to the rest of you as well), why not consider helping the site by becoming a writer? Contributors are only required to write 3 articles a month and I think we could all use some well-written technical articles by top web developers.

  • pceasies

    http://pceasies.com/?p=312

    There’s the CSS way, I believe I did it correctly

  • pceasies

    I think he may have been confused and put language instead of type. Type is required for the HTML <script> attribute</script>

  • ehynds

    Do actual research this time and don’t copy and paste the first CSS tutorial you find on Google. The fact that people might actually take your advice in this article – like Coaldead – makes me want to vomit.

    You guys definitely underestimate the value of thoughtful, authoritative articles. Instead of writing the shittest “tutorials” to spam the word JavaScript, while completely decrediting yourselves in the process, try writing something that people will want to share, bookmark, and keep coming back to.

  • Rob

    Agreed. This was a shameless traffic grab. Very disappointed in MUO for this one.

  • Steve Campbell

    I couldn’t disagree with you more. I’m afraid you’ve mistaken my lack of
    programming knowledge for laziness. I assure you I do research all of my
    articles beforehand with the intent of putting out quality work. I’ve
    written nearly 50 articles now for MUO and this is the first bad one I’ve
    come up with. Don’t think I’ve purposely come up with a dud here.

  • Steve Campbell

    I disagree as well. Most of the articles written are based on SEO research.
    Just because this one was based on an out-dated practice was only the fault
    of that research and a misunderstanding, don’t think it was a deliberate
    attempt to score traffic.

  • Lou

    Oh geez, just get over it people.

  • Lou

    Oh geez, just get over it people.

  • Yospos Bitch

    I too write shitty articles on topics I know nothing about for the ad revenue.

  • Yospos Bitch

    I too write shitty articles on topics I know nothing about for the ad revenue.