Jul
03
2009

A Simple Mouseover Hover Effect with jQuery

by   |  Posted in Tutorials  |  51 comments

JavaScript is pretty useful but it does demand a lot of coding. Luckily for all of us, there are libraries out there that make it extremely easy to use the power of JavaScript with a lot less code. I have been having a lot of fun with jQuery latetly and wanted to share a quick and easy tutorial on how to create a mouseover hover effect.

A similar effect can be easily accomplished using CSS and the :hover selector, but if you are new to jQuery, this tutorial is a good starting off point to familiarize yourself with how it works.

First you need to download jQuery. Grab the Production minified version off of their site. You will also need two images. I used the two below. I named them button.png and button-hover.png.

bavota-bwbavota

Now we can start to create the effect.

To make it all work, we first need to add the jQuery library script between the <head> tags.

<script type='text/javascript' src='http://yoursite.com/jquery.js'></script>

Now lets create the function that will make it all work.

<script  type='text/javascript'>
$(document).ready(function(){
	$(".button").hover(function() {
		$(this).attr("src","button-hover.png");
			}, function() {
		$(this).attr("src","button.png");
	});
});
</script>

Last but not least, we need to add our image to the page.

<img src="button.png" alt="My button" class="button" />

The one thing you need to make sure is that the classname in the jQuery function (.button) matches the classname of the image tag (button).

With everything in place you should have a file that looks like this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery Hover Effect</title>
<script type='text/javascript' src='http://yoursite.com/jquery.js'></script>
<script type='text/javascript'>
$(document).ready(function(){
	$(".button").hover(function() {
		$(this).attr("src","button-hover.png");
			}, function() {
		$(this).attr("src","button.png");
	});
});
</script>
</head>
 
<body>
<img src="button.png" alt="My button" class="button" />
</body>
</html>

Try out the effect below.

bavota-bw

NOTE: If you are using jQuery with WordPress, you need to replace all the dollar signs ($) with the word jQuery due to other Javascript libraries that use the dollar sign.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , ,

Short URL: http://bit.ly/aVtQ1r

Discussion 51 Comments

  1. Marek on July 7, 2009 at 5:13 am

    Do you think that Java script is the right choice..? even though thank you for tip

    • c.bavota on July 7, 2009 at 3:27 pm

      The only reason I like using Javscript is that it is cross browser compatible, as opposed to some CSS.

    • dan on June 25, 2010 at 12:35 pm

      It is browser compatible if they have js turned on. Why not just use css:hover? I know it won’t work in IE6, but IE6 won’t be a problem forever.

    • Wes W on November 14, 2010 at 7:10 pm

      in the 90′s javascript was the only way to do mouseovers, and now with all the cross browser issues in CSS it seems like the right choice again to me.

    • Jason on January 22, 2011 at 8:00 pm

      Javascript is definitely not the right choice for a simple hover.

      Just use a css sprite and change the background-position.

      img {background:url(“image.png”) 0 0 no-repeat scroll transparent}
      img:hover {background-position:center bottom}

    • moresco on February 27, 2011 at 9:19 am

      I think the idea here is that it’s a tip for use with JQuery, it’s not a tip for just a simple hover. If that’s all anyone wants, then sure, they can use CSS for that. But, if you’re already using JQuery, then a JQuery hover is the way to go.

      You can also do a simple hover with Flash, but that’s not what the tip is about.

      As for javascript being turned on, why would you turn it off? If you don’t trust scripts, get no-script or browser equivalent. There’s one for Chrome now, too. Cheers.

  2. Money Off Shop on July 9, 2009 at 5:50 pm

    Thanks for sharing this – it works great :) I’m curious though, when hovering over the initial grey button image would it be possible to replace it with some plain text (no image) rather than the red button image? Any help or pointers would be greatly appreciated. Many thanks :)

    • c.bavota on July 11, 2009 at 3:59 pm

      Hmm. I don’t know right off hand as I am still getting use to working with jQuery. But I am sure it is possible.

  3. ignacio on July 17, 2009 at 8:43 am

    many many thanks ! It’s working perfectly !

  4. The Watermark Group on July 17, 2009 at 3:44 pm

    This is just what I’ve been looking for. I’m code-phobic though, any idea on how to make the image into a link? Just <a href….?

  5. nana on July 30, 2009 at 4:29 am

    Is that possible to make this work in IE6…?

    Thanks!

  6. Matthew Hill on July 31, 2009 at 6:47 pm

    Hmm, javascript isn’t the best way to induce a hover effect, w3schools’ latest survey revealed 5% of people still browse the web with javascript turned off!

    Also, only ridiculously ancient browsers can’t render a basic css hover effect and if they are that old, they certainly won’t be able to render a jQuery .hover function!

    The best way to achieve the effect you want is definitely with a bit of CSS, like so:
    .button a, .button a:visited {width:89px;height:97px;background:(img/button.png);display:block}
    .button a:visited:hover, .button a:hover, .button a:active {background:(img/button_hover.png)}

    Then the (X)HTML;
    <div class="button"><a href="#"></a></div>

    Mat.
    http://www.matthewhill.name

    • Jeff on February 12, 2010 at 2:01 pm

      We’ve found that using CSS is preferable, but there are cases when the client wants the page to print just like it shows on-screen without extra steps by the user. In those cases, the CSS method won’t work because the buttons are using the background property and the majority of browsers default to “not print background images”.

      Maybe there is a CSS trick that I’m missing that addresses the printing issue, but I haven’t run across it.

    • flavius on March 12, 2010 at 11:18 am

      @Jeff,

      ever heard of @print css?

  7. Web Hosting on August 4, 2009 at 3:31 pm

    Very interesting post. I used CSS for hover effects. My result was compatible with all major browsers including IE6, but the loading time of the second picture was really big. I will try with this javascript. Thanks for your great post!

  8. c.bavota on August 5, 2009 at 11:00 am

    I wanted to use this post as an intro to show something simple. Next up is using jQuery to create a fade in and out effect.

  9. Carl on August 28, 2009 at 4:40 am

    Hey, very interesting.
    what if we want to publish more than one button or image with thata effect, do we have to write a script function for every image?
    Thanks.

    • c.bavota on August 31, 2009 at 10:42 am

      Hey Carl,

      This code wouldn’t really work with multiple images. Let me see if I can put together a tutorial for that.

  10. Cat Lady on November 1, 2009 at 10:23 pm

    Thank you sooooo much for this! I needed something that wasn’t going to give me the ugly black background issue because of the filters issue – this is perfect! You rock :)

  11. Louise on November 11, 2009 at 7:29 am

    I like the code, very simple. But, how can I add a setting to slow down the hover effect…it is instant right now and I’d like to see a bit more animation by slowing the transition between the 2 images?

    Louise

  12. Kevin on November 15, 2009 at 11:04 pm

    I am sorry but I can’t understand why you would use jQuery to perform a simple image replacement hover effect. You need to reference jquery and an external js file calling the effect. It makes no sense. Just do it with CSS. If a browser is not CSS compatible, do you really expect it be able to perform this effect with jQuery?

    • c.bavota on November 16, 2009 at 12:28 pm

      This is a basic tutorial on how to use jQuery to do something as simple as a hover effect. If you check out the next jQuery tutorial I have, Creating a Mouseover Fade Effect with jQuery, it shows how to take this to the next level and make it an animated fade effect.

  13. Atas??zleri on February 16, 2010 at 4:41 pm

    Wow, wonderful effect, thank you very much!

  14. Fashion & Lifestyle on February 22, 2010 at 11:11 am

    It¬¥s working perfectly! Thx in advance. Long time searching for this effect – easy to handle

  15. sadri on February 27, 2010 at 5:57 am

    This can be done with css but using javascript is good method too

  16. Alex Koloskov on March 25, 2010 at 12:05 pm

    Thank you for the script!

    I’ve modified it a little, using fade script (which was not working well on my template due to a layer absolute positioning): added a dynamic image loader, so if you have multiple images in the post, you do not need to have multiple scripts. Just make “after” image name by adding “_h” to the original “before” image name.

    Here it is, placed in the header.php on my wordpress:

          jQuery(document).ready(function(){  
              jQuery(".hov").hover(function() {  
                  jQuery(this).attr("src",function() {  return this.src.substring(0,this.src.length-4)+ '_h.jpg'});  
                    }, function() {  
                jQuery(this).attr("src",function() {  return  this.src.substring(0,this.src.length-6)+ '.jpg'});  
             });  
         });

    and the usage:

    <img class=”hov” src=”image.jpg” width=”600? height="812"  />

    The other image name is image_h.jpg

    Also, It is good to preload all the images, so it will flip on mouseover immediately:

    .preload {
    position:absolute;
    top:0px;
    left:0px;
    width:1px;
    height:1px;
    visibility:hidden;
    overflow:hidden;
    }

    Usage (in a post), only hover images need to be preloaded (with _h):

    <div class="preload">
    <img src="IMAGE_TO_PRELOAD_1_h.jpg" />
    <img src="IMAGE_TO_PRELOAD_2_h.jpg" />
    <img src="IMAGE_TO_PRELOAD_3_h.jpg" />
    </div>

    or you can use the line below, as my worpress editor for some reason erases “<div class=”:

    <div style="overflow: hidden; position: absolute; top: 0px; left: 0px; width: 1px; height: 1px; visibility: hidden;">
    <img src="image_h.jpg" alt="" />
    </div>

    Working example (1st image):
    http://www.perfectphotoblog.com/our-first-studio-workshop-and-master-class-in-atlanta/565/

    Hope this will help

  17. Rob Miracle on April 21, 2010 at 12:25 pm

    A couple of things: IE6 issues: The example uses a PNG file. IE6 can use PNG files fine, but if the PNG has a transparent background IE6 can’t deal with the transparency. Try a GIF file instead.

    Next: The image should have an ID and the Javascript/jquery should use the id instead of a class. ID’s are for unique elements where classes can cover multiple elements. Therefore, there could be multiple .button’s on the page. The code above would replace all images with a class of “button” with the same image, probably not an effect you want. Since the image src attribute should be unique for each button in most cases, using the id makes more sense.

  18. marathons on April 21, 2010 at 7:41 pm

    Thank heavens for the libraries that make Javascript that much easier. I’m not too fond of code…

  19. Filipe on June 20, 2010 at 9:12 am

    Oh my god, not need this… someone css resolv

    • Filipe on June 20, 2010 at 9:14 am

      Only css*

  20. wie ajuz on July 23, 2010 at 7:59 pm

    Great hover efect , really simple
    but i like it
    thanks

  21. Shuriken Marketer on August 7, 2010 at 6:15 am

    Thanks for the tips. I will try this script out…
    Is there any way to make it shorter?

  22. jackiller on August 20, 2010 at 4:45 am

    nice hover effect. thank you for this tutorials.

  23. Ayd?n Yakar on August 23, 2010 at 7:47 am

    Nice and helpful, thank you..

  24. koltuk y?kama on October 3, 2010 at 11:43 am

    you are very helpful thanks.

  25. Repossession on November 22, 2010 at 8:52 am

    Very helpful article. Is there any plugin for this?