Search code examples
javascriptjqueryimagehoverjquery-hover

Change Image on Hover using jQuery and an Image Map


I have an image that I am using an image map on. When hovering over part of the image depending on the map I want the image to change and I am not sure how to go about doing this using jQuery. Here is the code I have attempted:

HTML:

 <div class="img-center">
  <img src="img-src_off.jpg" usemap="#Map" class="feature-image" border="0" />
    <map name="Map" id="Map">
      <area shape="rect" coords="77,461,391,492" href="#" target="_blank"
            class="link-1" />
      <area shape="rect" coords="557,461,855,490" href="#" target="_blank" 
            class="link2" />
    </map>
 </div>

JS:

Note: This is the JS I have attempted but errors are thrown (errors listed below) and I do not know what to try now. I do not have to use this code if I can find a code that works without issue.

var $j = jQuery.noConflict();
  $j(document).ready(function() {
     $j.preLoadImages("img_src_01.jpg",
                     "img_src_02.jpg"
     ); 

     $j(".link1").hover(function(){
        this.src = this.src.replace("_off","_01");
        },
        function(){
        this.src = this.src.replace("_01","_off");
        }
     );

           $j(".link2").hover(function(){
        this.src = this.src.replace("_off","_02");
        },
        function(){
        this.src = this.src.replace("_02","_off");
        }
     ); 
   });

  (function(j$) {
    var cache = [];
    $j.preLoadImages = function() {
      var args_len = arguments.length;
      for (var i = args_len; i--;) {
        var cacheImage = document.createElement('img');
        cacheImage.src = arguments[i];
        cache.push(cacheImage);
      }
    }
  });

The errors I see are as follow:

TypeError: this.src is undefined
[Break On This Error]   

this.src = this.src.replace("_off","_01");

(this error repeats itself on every hover)

And this error:

TypeError: $j.preLoadImages is not a function
[Break On This Error]   

"img_src_02.jpg"

Please provide examples when answering as I am not very fluent in Javascript.


Solution

  • To write a jQuery plugin, start by adding a new function property to the jQuery.fn object where the name of the property is the name of your plugin:

    Try the following:

    (function($j) {
       $j.fn.preLoadImages = function() {
            //...
       }
    })(jQuery);