JQuery Image rollover on Mouse hover: Tutorial

In this quick tutorial, I would explain how to implement image rollover on mouse hover on a class or button.

Jquery Hover()

We are using Jquery Hover() API to implement image rollover. The syntax of the hover() API is:
hover( handlerIn(eventObject), handlerOut(eventObject) )

So, we can attach 2 functions to the jquery hover() API, one we hover over a certain html element and other when we move out.

Jquery Image Rollover

Suppose we have a submit button that has class .submit and we want to change image name from roll.png to roll-hover.png when we hover over it. Following is the jquery code we would use to do it. (Note that can more easily be done through CSS, but implementing jquery solution can generalize the functionality across the website)
function(){ // Change the image name when we hover.
var t = $(this);
t.attr(‘src’,t.attr(‘src’).replace(/([^.]*)\.(.*)/, “$1-hover.$2″));
var t= $(this);


In the jquery code above, .hover() is the jquery API function called upon hover. Here, we are using Jquery regular expression to search and replace the image name by adding “-hover” to it.

Meaning of Jquery Regular Expression

Jquery regular expression in the JQuery replace() API function:

replace(/([^.]*)\.(.*)/, "$1-hover.$2")


means as follows:
[1] ([^.]*) : It says match all characters except . [ period ]
[2] \. : match a period
[3] (.*) : matches any character

so it becomes [1]Match all characters which are not . [ period ] [2] till you find a .[ period ] then [3] match all characters.

Now, in Jquery replace() means add “-hover” to the first part which is stored in $1 and add remaining $2 of the image name into it.


When we move out from the .submit class, the other function is called which removes the perviously added -hover to the string of the image name:


Comments on this entry are closed.