Skip to main content

Attaching an event to multiple elements at one go



Say I have the following :







var a = $("#a");

var b = $("#b");



//I want to do something as such as the following :



$(a,b).click(function () {/* */}); // <= does not work



//instead of attaching the handler to each one separately







Obviously the above does not work because in the $ function, the second argument is the context , not another element.





So how can I attach the event to both the elements at one go ?








[Update]





peirix posted an interesting snippet in which he combines elements with the & sign; But something I noticed this :







$(a & b).click(function () { /* */ }); // <= works (event is attached to both)



$(a & b).attr("disabled", true); // <= doesn't work (nothing happens)







From what you can see above, apparently, the combination with the & sign works only when attaching events...?



Source: Tips4all

Comments

  1. The jQuery add method is what you want:


    Adds more elements, matched by the given expression, to the set of matched elements


    var a = $("#a");
    var b = $("#b");
    var combined = a.add(b)

    ReplyDelete
  2. Don't forget either that jQuery selectors support the CSS comma syntax. If you need to combine two arbitrary collections, everyone else's suggestions are on the mark, but if it's as simple as doing something to elements with IDs a and b, use $('#a,#b').

    ReplyDelete
  3. You could just put them in an array:

    $.each([a, b], function()
    {
    this.click(function () { });
    });

    ReplyDelete
  4. I just tried messing around with this, and found something very cool:

    $(a & b).click(function() { /* WORKS! */ });


    supersweet!

    Edit: Now I feel really embarrassed for not testing this properly. What this did, was actually to put the click event on everything... Not sure why it does that, though...

    ReplyDelete
  5. This question has already been answered, but I think a simpler more streamlined way to accomplish the same end would be to rely on the similarities between jQuery's and CSS's selector model and just do:

    $("#a, #b").click(function () {/* */});


    I use this frequently, and have never seen it not work (I can't speak for jQuery versions before 1.3.2 though as I have not tested this there). Hopefully this helps someone someday.



    UPDATE: I just reread the thread, and missed the comment you made about having the nodes in question already saved off to variables, but this approach will still work, with one minor tweek. you will want to do:

    var a = $("#a");
    var b = $("#b");
    $(a.selector+", "+b.selector).click(function () {/* */});


    One of the cool things that jquery does is that it adds a few jquery specific properties to the node that it returns (selector, which is the original selector used to grab that node is one of them). You may run into some issues with this if the selector you used already contained commas. Its also probably arguable if this is any easier then just using add, but its a fun example of how cool jquery can be :).

    ReplyDelete
  6. try this: sweet and simple.

    var handler = function() {
    alert('hi!');
    }
    $.each([a,b], function() {
    this.click(handler);
    }


    BTW, this method is not worth the trouble.

    If you already know there are just two of these methods, then I guess the best bet would be

    a.click(handler);
    b.click(handler);


    Cheers!

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.