Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery attr() change img src

I'm making some Rocket launching effect by jQuery. When I click on Rocket, it'll swap with another rocket image, and then launch up. When I click "Reset" link, Rocket must reset starting location and image must revert back. But there are two problems. First, "my rocket image is not reverting back". Second - after it's reverted to initial location, if I click on Rocket again, it's not launching. Can you see and find me solutions?

http://jsfiddle.net/thisizmonster/QQRsW/

$("#resetlink").click(function(){
    clearInterval(timerRocket);
    $("#wrapper").css('top', '250px');
    $("#rocket").attr('src', 'http://www.kidostore.com/images/uploads/P-SAM-rocket-blk.jpg');
});

You can see $("rocket").attr() row.

like image 829
Gereltod Avatar asked May 13 '11 03:05

Gereltod


1 Answers

You remove the original image here:

newImg.animate(css, SPEED, function() {
    img.remove();
    newImg.removeClass('morpher');
    (callback || function() {})();
});

And all that's left behind is newImg. Then you reset link references the image using #rocket:

$("#rocket").attr('src', ...

But your newImg doesn't have an id attribute let alone an id of rocket.

To fix this, you need to remove img and then set the id attribute of newImg to rocket:

newImg.animate(css, SPEED, function() {
    var old_id = img.attr('id');
    img.remove();
    newImg.attr('id', old_id);
    newImg.removeClass('morpher');
    (callback || function() {})();
});

And then you'll get the shiny black rocket back again: http://jsfiddle.net/ambiguous/W2K9D/

UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:

$("#resetlink").click(function(){
    clearInterval(timerRocket);
    $("#wrapper").css('top', '250px');
    $('.throbber, .morpher').remove(); // Clear out the new stuff.
    $("#rocket").show();               // Bring the original back.
});

And in the newImg.load function, grab the images original size:

var orig = {
    width: img.width(),
    height: img.height()
};

And finally, the callback for finishing the morphing animation becomes this:

newImg.animate(css, SPEED, function() {
    img.css(orig).hide();
    (callback || function() {})();
});

New and improved: http://jsfiddle.net/ambiguous/W2K9D/1/

The leaking of $('.throbber, .morpher') outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.

like image 166
mu is too short Avatar answered Nov 01 '22 23:11

mu is too short