Tamil
Tamil

Reputation: 5358

Attaching Event Handlers Optimization JavaScript

<div id='test'>
 <a href='#'>Link 1</a>
 <a href='#'>Link 2</a>
 <a href='#'>Link 3</a>
 <a href='#'>Link 4</a>
 <a href='#'>Link 5</a>
 <a href='#'>Link 6</a>
 <a href='#'>Link 7</a>
 <a href='#'>Link 8</a>
 ...
 <a href='#'>Link n</a>
</div>

How to handle onclick event on all anchor tags [30 < n < 50]. Is it good to attach onclick event on individual anchor tags? I can't use any JavaScript libraries. It would be helpful to know jQuery handle $('.test a').click() it. How are they able to pass proper this attribute?

Upvotes: 0

Views: 392

Answers (3)

bfavaretto
bfavaretto

Reputation: 71908

You could delegate click handling to the div, then check the target inside the handler and act according to which anchor was clicked.

var div = document.getElementById('test');
div.addEventListener('click', function(event){
    console.log(event.target.innerHTML)
});

http://jsfiddle.net/nrVS9/

Warning: IE versions before 9 do not support addEventListener. If you need to support those browsers, check if addEventListener is available, and use attachEvent if it's not.

Upvotes: 2

zatatatata
zatatatata

Reputation: 4821

I'd recommend using something like the following:

function callback(e) {
    var e = window.e || e;

    if (e.target.tagName !== 'A')
        return;

    // Do something
}

if (document.addEventListener)
    document.addEventListener('click', callback, false);
else
    document.attachEvent('onclick', callback);

In addition ofc, I'd recommend attaching a pseduo-attribute to each anchor that has the number (1-50) so you could use that to detect which of the anchors the user clicked.

you can set this by calling function with function.call(element, arg1, arg2, ...) or function.apply(element, [arg, arg2, arg3, ...])

Upvotes: 2

wong2
wong2

Reputation: 35720

document.getElementById('test').onclick = function(event){
    event = event || window.event;
    if(event.target.nodeName == "a"){
        console.log("link clicked");
    }
});

Upvotes: 1

Related Questions