0

I have a two 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: /CompleteEducation/images/icons/toggleIcon.png

Rollover Image: /CompleteEducation/images/icons/toggleIconDisabled.png

I have used following code but this code overwrite the name:

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

How can I do it using jQuery?

lowtechsun
  • 1,915
  • 5
  • 27
  • 55
Kashif Hashmi
  • 75
  • 1
  • 2
  • 10
  • possible duplicate of [Change the image source using jQuery](http://stackoverflow.com/questions/540349/change-the-image-source-using-jquery) – Sid M Aug 05 '14 at 10:44

3 Answers3

0

You say on each mouseover, check if the current images' attribute SRC contains the file name you like. And if yes, then you change the source. You can though replace my sample strings if they are wrong.

My Html:

<img src='http://velocityagency.com/wp-content/uploads/2013/08/go.jpg' width='500' >

My JS:

// make sure you have put your code inside the Document.ready
$(document).ready(function(){

    $("img").on("mouseenter", function(){


    if($(this).attr("src").indexOf("go.jpg") !== -1) // we check if the path contains the name of the image at all
    {
       var att = $(this).attr("src"); // we then pull the src attr
       att = att.replace("go.jpg", "iPAd.jpg"); //and search for the filename and replace new file name

       // in the end we assign the new imagepath to the src of the hovered image
       $(this).attr("src", att);
    }
});
});

Check this fiddle or the code above:

http://jsfiddle.net/F72h3/

Mostafa Talebi
  • 8,825
  • 16
  • 61
  • 105
0

You can change image using condition operator

$(function() {
    $("img")
        .mouseover(function() { 
            this.src = this.src.indexOf('Disabled.png') == -1 ?
               '/CompleteEducation/images/icons/toggleIconDisabled.png' :
               '/CompleteEducation/images/icons/toggleIcon.png';
        })
});
Adil
  • 146,340
  • 25
  • 209
  • 204
0

I think problem is here

 var src = $(this).attr("src").match(/[^\.]+/) + "toggleIconDisabled.png"; //this will return "/CompleteEducation/images/icons/toggleIcontoggleIconDisabled.png"

try this

var src = ($(this).attr("src").indexOf("Disabled")>-1)?"/CompleteEducation/images/icons/toggleIcon.png":"/CompleteEducation/images/icons/toggleIconDisabled.png";
Mritunjay
  • 25,338
  • 7
  • 55
  • 68