Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the image source on rollover using jQuery

Tags:

html

jquery

I have a few images and their rollover images. Using jQuery, I want to show/hide the rollover image when the onmousemove/onmouseout event happen. All my image names follow the same pattern, like this:

Original Image: Image.gif

Rollover Image: Imageover.gif

I want to insert and remove the "over" portion of image source in the onmouseover and onmouseout event, respectively.

How can I do it using jQuery?

like image 839
Sachin Gaur Avatar asked Feb 12 '09 07:02

Sachin Gaur


People also ask

How to change image on mouseover in jQuery?

mouseover(function () { var imgName = $(this). find('img'). attr('src'); var img2 = imgName. substring(0, imgName.

How to change image using jQuery?

Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.

How do I change the source of an image in JavaScript?

Change the Source of an Image Using the src Property in JavaScript. To change the source or src of an image, you need to add an id or class to the image tag. You can get the image element using the name of the id or class , and you can change the source or src of the image using the src property.


2 Answers

To set up on ready:

$(function() {     $("img")         .mouseover(function() {              var src = $(this).attr("src").match(/[^\.]+/) + "over.gif";             $(this).attr("src", src);         })         .mouseout(function() {             var src = $(this).attr("src").replace("over.gif", ".gif");             $(this).attr("src", src);         }); }); 

For those that use url image sources:

$(function() {         $("img")             .mouseover(function() {                var src = $(this).attr("src");                var regex = /_normal.svg/gi;                src = this.src.replace(regex,'_rollover.svg');                $(this).attr("src", src);              })             .mouseout(function() {                var src = $(this).attr("src");                var regex = /_rollover.svg/gi;                src = this.src.replace(regex,'_normal.svg');                $(this).attr("src", src);              });     }); 
like image 148
Jarrod Dixon Avatar answered Oct 02 '22 18:10

Jarrod Dixon


I know you're asking about using jQuery, but you can achieve the same effect in browsers that have JavaScript turned off using CSS:

#element {     width: 100px; /* width of image */     height: 200px; /* height of image */     background-image: url(/path/to/image.jpg); }  #element:hover {     background-image: url(/path/to/other_image.jpg); } 

There's a longer description here

Even better, however, is to use sprites: simple-css-image-rollover

like image 31
Tyson Avatar answered Oct 02 '22 18:10

Tyson