views:

69

answers:

5

Hi,

I've written a quick image swap class that switches images on hover by placing adding '_grey' to the image src. The code works great throughout the site in all browsers apart from ie6. The substr doesnt seem to work properly here - any advice please!?

Code as follows -

$(document).ready(function() {
var initImg;    
    $('img.swapGrey').hover(function() {


        initImg = $(this).attr("src");  
        var imgType = (initImg).substr(-4);
        alert(initImg);
        var greyImg = initImg.slice(0, -4) + "_grey" + imgType;
        alert(greyImg);

        $(this).attr("src",greyImg);

            }, function() {
        $(this).attr("src",initImg);

    });


});
A: 

Try putting your code in load event rather than ready:

$(window).load(function(){
  // your code...
});

The reason for using load event is that by the time images have completely loaded into the page unlike ready event.

Sarfraz
should not matter to the mouseover event unless you are quite fast (visually), even then...not the issue as the DOM will have the attr src set.
Mark Schultheiss
+1  A: 

just use a positive starting position in IE.

akonsu
+1  A: 

IE doesn't support negative values for the argument of substr.

RoToRa
+2  A: 

Use slice rather than substr. substr is non-standard, while slice is specified (including negative positions) in the ECMAScript 3 spec, and is supported in all the major browsers, including IE 6.

Tim Down
Works a treat, Cheers Tim
Paul
A: 

More verbose than needs to be (to show the effect of the functions), but basically changes test.jpg to test_grey.jpg if test.jpg is the src of the img element.

    $(document).ready(function() {
        var initImg;
        $('img.swapGrey').hover(function() {


            initImg = $(this).attr("src");
            var len = initImg.length - 4;
            var imgType = initImg.slice(len);
            alert(":"+imgType+":");
            alert(initImg + " is " + len +":"+ imgType);
            var greyImg = initImg.slice(0, -4) + "_grey" + imgType;
            alert(greyImg);

            $(this).attr("src", greyImg);

        }, function() {
            $(this).attr("src", initImg);
      });
 });
Mark Schultheiss