user648340
user648340

Reputation:

One element, multiple events

In jQuery you can easily do it like this:

$("#foo").focus(function () {
    // Do this.
}).blur(function () {
    // Do that.
});

Can we do something similar in pure JavaScript so we don't have to repeat #foo in two separate functions?

Upvotes: 1

Views: 56

Answers (1)

Ry-
Ry-

Reputation: 224905

Use a variable; really!

var foo = document.getElementById('foo');

foo.addEventListener('focus', function () {
    // Do this.
});

foo.addEventListener('blur', function () {
    // Do that.
});

Or a helper, if you prefer:

function on(eventSource, listeners) {
    for (var k in listeners) {
        if (Object.prototype.hasOwnProperty.call(listeners, k)) {
            eventSource.addEventListener(k, listeners[k]);
        }
    }
}

on(foo, {
    focus: function () {
        // Do this.
    },
    blur: function () {
        // Do that.
    }
});

Or a chaining helper:

function chainOnly(obj) {
    var wrapper = {};

    function createChainWrapper(func) {
        return function wrapped() {
            func.apply(obj, arguments);
            return wrapper;
        };
    }

    for (var k in obj) {
        if (typeof obj[k] === 'function') {
            wrapper[k] = createChainWrapper(obj[k]);
        }
    }

    return wrapper;
}

chainOnly(foo)
    .addEventListener('focus', function () { /* … */ })
    .addEventListener('blur',  function () { /* … */ });

Upvotes: 4

Related Questions