Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind event to multiple elements without looping (vanilla JS)

Tags:

javascript

I'm trying to achieve the equivalent of:

$('div').on('click', function() {
    // Do something
});

But without jQuery. My initial thought was to use a for loop to iterate over all elements in the set, but my guess is there's a better way of achieving this without using a loop (some native method?).

var elems = document.getElementsByTagName('div');

function someEvent() { // Generic function to test against
    alert('event fired');
}

for (var i=0, j = elems.length; i < j; i += 1) {
    elems[i].addEventListener("click", someEvent);
}

Is there a more elegant way of doing this without the inclusion of a library?

like image 592
monners Avatar asked Dec 14 '13 05:12

monners


1 Answers

What you want is event delegation. It works by binding a single event to a parent of multiple nodes, and analyzing the event's target node. For example, you can bind onmouseup to the body node, and when it is triggered from releasing the mouse on a div node, the body event object will contain that div in the target property. You can analyze the target to make sure it matches certain criterias.

A better way to explain this, is to just provide a working example.

document.body.onmouseup = function (event) {
    var target = event.target || event.toElement;

    if (target.nodeName.toLowerCase() == "div") {
       alert(target.childNodes[0].nodeValue);
    };
};

The main point of interest with this example is the target variable, and the condition to verify that our target is a div. The condition can even be a className or anything your heart desires.

like image 157
Shea Avatar answered Nov 04 '22 07:11

Shea