3

How do you add a jquery click event handler for a bunch of links within a div? For example:

<div class="test">
<a href="test1.html">link 1</a>
<a href="test2.html">link 2</a>
<a href="test3.html">link 3</a>
</div>

I'd like to add a click event handler for each of the three links, so I can addClass('selected') to the link that was clicked on and removeClass('selected') from the rest.

I know I can do them one by one, but I was wondering what the cleanest way to do this is...

Prabhu
  • 12,995
  • 33
  • 127
  • 210

5 Answers5

7

I would use .delegate():

var classname = 'selected';

$('div.test').delegate('a', 'click', function ()
{
    $(this).addClass(classname).siblings().removeClass(classname);
});
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 1
    Why delegate()? He did not say he was going to add more "div.test a" to the DOM? – Kris Krause Sep 30 '11 at 21:13
  • In general, it's better to bind fewer event handlers. Older versions of IE and mobile browsers appreciate it. – Matt Ball Sep 30 '11 at 21:13
  • Is this any different than `$('div.test a').bind('click', function [etc]);` ? – Stephen P Sep 30 '11 at 21:14
  • @Matt - I see the "or in the future" as a big difference, but the "for all elements that match the selector" suggests (to me) that you wouldn't get fewer event handlers this way vs. 'div.test a' – Stephen P Sep 30 '11 at 21:16
  • 1
    @StephenP `.delegate()` works by binding a single event listener to the selected element(s). That's how the "in the future" part is implemented - it takes advantage of event bubbling. It is very similar to `.live()`: http://stackoverflow.com/questions/6801070/how-does-jquery-live-work – Matt Ball Sep 30 '11 at 21:20
5

The selector will return an array of elements that match.

$('div.test a')

will be the tree links.

$('div.test a').click(function() { });

Will bind to all three.

Joseph Yaduvanshi
  • 20,241
  • 5
  • 61
  • 69
2

Selectors work like CSS selectors, so this selects a tags inside tags with class test

$('.test a').click(function(){

    // select the object that was clicked on
    $(this)
        // add the selected class to it
        .addClass('selected')
        // remove the selected class from it's brothers and sisters
        .siblings().removeClass('selected')

    // stop link from loading and resetting page
    return false

})

Demo here: http://jsfiddle.net/HK6CE/

Billy Moon
  • 57,113
  • 24
  • 136
  • 237
1

I would write (with no extra markup):

$('.test a').bind('click', function() {

$(this).addClass('selected').siblings().removeClass('selected');

});

Siblings() gets all the others dom elements on the same level, so it'll get all the others "a" inside .test

maxijb
  • 541
  • 4
  • 13
0

I believe it's $('.test').each(function(){})

mowwwalker
  • 16,634
  • 25
  • 104
  • 157