Last Updated: February 25, 2016
·
681
· _faz

What's behind $.bind ?

HTML

<a href="#" id="link">Click me !</a>

JS

var a = document.getElementById('link');

    if (a.addEventListener) {
        a.addEventListener("click", callback, false);
    } else if (a.attachEvent) {
        a.attachEvent("onclick", callback);
    }

    function callback (e) {
        var target = e.target || e.srcElement;

        if (target.innerHTML == 'Hello World!') {
           target.innerHTML = 'Bonjour Monde !';
        } else {
            target.innerHTML = 'Hello World!'; 
        }

        if (e.stopPropagation) {
            e.stopPropagation()  
        }

        if (e.preventDefault) {
            e.preventDefault()  
        }
        return false;
    }

2 Responses
Add your response

That's not completely true. $().bind also keeps a list of all events and handlers attached to an element, and does various other little tidbits, such as passing a normalized event object. Knowing that addEventListener is the pure-DOM version of $().bind is half the battle: the various differences between them are what is really interesting.

over 1 year ago ·

Totally true.
I just wanted to partially show how simply binding without jQuery.
My intention wasn't to give a $.bind pure-DOM equivalent.

over 1 year ago ·