Building a better image mouseover using jQuery

2
Building a better image mouseover using jQuery

jQuery is a very versatile library when it comes to manipulating the DOM and proved to be instrumental in creating an image mouseover script recently for a friend’s website. I feel as though what I created is rather elegant, so I decided to explain how to create it below.

About 8 – 10 years ago, I remember having to create an image mouseover script about which involved about 50 lines of JavaScript and using inline onClick. To say the least, it was messy and you can achieve something similar with about only 8 lines of code!

I will be using two different images for the mouseover:
tv_off.gif and tv_on.gif

  1. First, create the HTML
    <ul>
    <li><a href="/tv"><img src="images/tv_off.gif" class="mainnav"></a></li>
    </ul>
    
  2. Select the .mainnav class and attach a hover event handler to it.
    $(".mainnav").hover(
      function () {
      },
      function () {
      }
    );
    
  3. Setup a variable called imgPath and assign the src of the image
    $(".mainnav").hover(
      function () {
        // Grab the source
        var imgPath = $(this).attr("src");
      },
      function () {
        // Grab the source
        var imgPath = $(this).attr("src");
       }
    );
    
  4. The last step involves using the replace JavaScript method to find the string “off” and replace it with “on” and vice versa for hover on/off.
    $(".mainnav").hover(
      function () {
        // Grab the source
        var imgPath = $(this).attr("src");
        // Replace the path in the source
        $(this).attr("src",imgPath.replace("off", "on"));
      },
      function () {
        // Grab the source
        var imgPath = $(this).attr("src");
        // Replace the path in the source
        $(this).attr("src",imgPath.replace("on", "off"));
       }
    );
    

    It’s that easy!

  1. Your script won't work if the image name itself contains texts "on" or "off". It would be better if you can store the mouseover and mouseout image names as data attributes for the img tag.

LEAVE A REPLY