JSFiddle - React, Tailwind, and code Playground

by Ilmv

HTML

<img id="photo" src="" alt="Google Logo" />

<br />
<a href="#" id="load-btn">Load</a><br />
<a href="#" id="remove-btn">Remove</a>

<div id="output"></div>

JavaScript

var load_btn = $('#load-btn'),
    remove_btn = $('#remove-btn'),
    photo = $('#photo'),
    path = 'http://www.google.co.uk/images/srpr/logo2w.png',
    output = $('#output');

load_btn.click(function(e) {   
    photo.attr('src', path);
    // remember your binds are persistant, each click you're adding yet another bind
    // unbind the load event before you add another.
    // you could namespace this bind, but that might be taking it too far
    photo.unbind('load').load(function() {
        log('loaded image');
    });
    e.preventDefault();
});

remove_btn.click(function(e) {
    photo.attr('src', '').trigger('unload');
    log('unload image');
    e.preventDefault();
});

function log(str)
{
    output.append(str + '<br />');
}

/*
if you click "Load", it will load in the image from Google and write out "loaded image".
now click "Remove", this will remove the image.
clicking "Load" again, loads the image back in, but fires the load method attached to it twice.

any ideas how to improve the unloading method so that this doesn't happen?
*/