5

Issue: YUI3 - Onclick event handling for links having same classes

We have few links in the page having same class. When I click on one of the links there are some different actions to be taken based on the which link was clicked, For e.g.

<a href="?page=1" data="test1" class="sample">One</a>
<a href="?page=2" data="test2" class="sample">two</a>
<a href="?page=3" data="test3" class="sample">three</a>

handler code:

Y.all('.sample').on('click', function(e){
    e.preventDefault();
    alert(this.getAttribute("data"));
});

when I click any of the links I get the list of all "data" attribute. We only need the data of link clicked.

Neo
  • 5,070
  • 10
  • 46
  • 65

3 Answers3

3

You can also use e.target instead of this to access the element being clicked:

Y.all('.sample').on('click', function(e){
  e.preventDefault();
  alert(e.target.getAttribute("data"));
});

And for even better performance you can use event delegation:

Y.one('body').delegate('click', function(e){
  e.preventDefault();
  alert(this.getAttribute("data"));
}, '.sample');
juandopazo
  • 6,283
  • 2
  • 26
  • 29
1

all gives you a list of matched elements. You can use each to iterate through the list and do stuff for individual node. Refer to their Node Class API for more information.

Here is the code, and an example on jsfiddle.

Y.all('.sample').each(function(node) {
    node.on('click', function(e) {
        e.preventDefault();
        alert(node.getAttribute("data"));
    });
});​

There is also a FAQ entry for this question in the Event user guide on yuilibrary.com (http://yuilibrary.com/yui/docs/event/#nodelist-this). It's generally preferable to use event delegation.

Community
  • 1
  • 1
322896
  • 956
  • 1
  • 9
  • 19
  • @user322896: How well is your YUI skills? I'm struggling to get my question answered. You care to advise? – Brendan Vogt Aug 01 '12 at 17:08
  • @BrendanVogt Which question are you struggling with? I'll try to help. – 322896 Aug 01 '12 at 17:58
  • Thanks. On YUI forum: http://yuilibrary.com/forum/viewtopic.php?f=92&t=10372 and on SO: http://stackoverflow.com/questions/11701804/yui3-button-click-event-is-acting-like-a-submit-type-instead-of-a-button-type – Brendan Vogt Aug 01 '12 at 18:07
0

Here event delegation is better solution, agree with @juandopazo

If you do not want to use delegation, you can use Y.all('.sample').each(...) (solution from @user322896) or e.target (solution from @juandopazo), but I usually do it another way:

Y.on('click', function(e){
    e.preventDefault();
    alert(this.getAttribute("data"));
}, '.sample');

This is not a delegation syntax (listeners will be attached on links directelly) and there is no NodeList object, so this refers to particular link node. This way is also have preformance advantage comparing to Y.all('.sample'), read this: Why would I use Y.on() or Y.delegate() instead of node.on() and node.delegate()?

Petr
  • 7,275
  • 2
  • 16
  • 16