Search code examples
javascriptimagesrcimage-replacement

Errors with an image replacement


I have tried every possible combination of methods for replacing an image but have found no solution that works.

I uploaded the problematic code here: http://dl.dropbox.com/u/2959730/index.html

I would suggest downloading the source and trying your code. The problem lies with the player.playPause() function that should be attached to the #playButt img.

Please help I've been struggling for hours now!

EDIT:

I've corrected everything and as per suggestion I'm using this code now for playPause(), but it still doesn't work!. This is the most frustrating thing I have ever dealt with...

this.playPause = function(){  
    this.status = !this.status;  
    var status = this.status;
    var playEl = document.getElementById('play');
    $("#play").fadeOut(200, function(){  
        if(status)  
            playEl.src = "img/pauseButton.png";
        else  
            playEl.src = "img/playButton.png";
        $("#play").fadeIn(200); 
    }) 
} 

Solution

  • playPause() is defined as a property of var player, in playlist.js.

    Your onclick onclick="playPause(); return false;" isn't calling playPause because it can't find the function in the global scope. You need to change your onclick to:

    onclick="player.playPause(); return false;"
    

    Update:

    The problem is with this callback:

    $("#play").fadeOut(200, function(){  
        if(this.status)  
            playEl.src = "img/pauseButton.png";
        else  
            playEl.src = "img/playButton.png";
    }).fadeIn(200);  
    

    this.status is undefined inside that callback since this now refers to the element #play. To fix this problem you need to declare var status = this.status before the callback, and test if(status) inside the callback.

    Two other things:

    1. The .fadeIn(200) should be placed inside the callback, otherwise it is running before the fadeOut completes (so there's no fade effect at all).
    2. You don't need var playEl = document.getElementById('play'); since you're using jQuery to grab the element. Inside the callback, the this keyword refers to the element already.

    The complete code should be:

    var status = this.status = !this.status;
    $("#play").fadeOut(200, function(){  
        if(status)  
            this.src = "img/pauseButton.png";
        else  
            this.src = "img/playButton.png";
        $(this).fadeIn(200);
    });
    

    Another Update:

    In addition to the above fix, there's a further problem. It looks like there are two elements on the page with id="play". In fact, the whole #ipod2 is duplicated. I checked the source code, but it's not there, only in the live DOM. If you $("#play").remove(); in the console, you'll see that the image replacement code now works. However, you'll need to find out where ipod2 is being cloned in the JS and fix that.