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

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex