Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

I have a few images and their rollover images. Using jQuery, I want to show/hide the rollover image when the onmousemove/onmouseout event happens. 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?

1 Answer

0 votes
by (40.7k points)

To set up on ready, try this:

$(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);

        });

});

If you are using url image sources, then use this:

$(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);

            });

    });

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...