Patrick Hansen.com

JQuery Image Button Example

May 13, 2010

Hover over an image to see the js change.

These images are located in different directories and have different names.

They are sharing the same script to alter the hover states.
The only requirements to ensure this works are:

  1. The obvious, must have current JQuery library file linked and the script either in the page or in external linked js file.
    Download JQuery Here
  2. Must assign the class, that the script references to the anchor tag for your button.
    (example: <a class=”js_uniButton” …></a> ).
    (You can change this class to whatever you'd like, but make sure that the reference in the script and the class you assign your anchors are the same.)
  3. The up and over images MUST have the same file name and be the same file type, but the over image must be appended with “_hover“.
    (example: MyImage.gif and MyImage_hover.gif)

Download this demo

The following script NEEDS to be within a doc ready function

function getHoverPath (imgPath) {
    //split imgPath after each '/' and create array to path directories and file name
    var srcPathArray = imgPath.split('/');
    
    //find image file name get length of srcPathArray and retrieve last item which is the image file ex: "images/buttons/IMG.gif"
    var imgFile = srcPathArray[srcPathArray.length-1];
    
    //image file name array split at "." to get:[fileName, ext]
    var imgArray = imgFile.split('.');
    
    //img name (first item in imgArray)
    var imgName = imgArray[0];
    
    //image ext (second item in imgArray)
    var imgExt = imgArray[1];
    
    //image src path
    var srcPath = imgPath.split(imgFile , 1);
    
    // concatenate path and add "_hover" to image file name
    return srcPath + imgName+'_hover.'+ imgExt;
    
    };
    // get hover button array
    var hoveredButtons = new Array();
    
    $('.js_uniButton').mouseover (function() {
    $this = $(this);
    
    //get image path of this instance
    var imgPath = $this.children('img').attr('src');
    
    //cache img path url on initial mouseover
    if (typeof(hoveredButtons[ imgPath ]) == 'undefined') {
        hoveredButtons[ imgPath ] = getHoverPath( imgPath );
        
        //console.log('cache image path ' + imgPath + ' and hover path ' + hoveredButtons[ imgPath ]);
     }
    $this.children('img').attr('src' , hoveredButtons[ imgPath ]);
    
    //mouseout actions
    $this.mouseout(function() {
        //define this handler
        var $this = $(this), handler = arguments.callee;
        
        //unbind mouseout handler
        $this.unbind('mouseout', handler);
        
        // on mouseout, swap current image with original image path
        $this.children('img').attr('src' , imgPath);
    });
});

JQuery image-based Button example:

Hover over image to see state change


CSS image-based button example (using the same images)