2

I have the following code:

var buttonOne = $("#buttonOne");
var buttonTwo = $("#buttonTwo");

// opens an already initialized modal window 
(buttonOne, buttonTwo).click(function()
{
    modalBoxContainer.dialog("open");
});

This is not working. It will work if I use the elements, but not with the variables.

Any ideas?

2
  • are you missing the $? your example is. Commented May 11, 2012 at 20:32
  • I was but that does not make a difference in this case. Commented May 11, 2012 at 20:43

2 Answers 2

9

Use the .add method.

buttonOne.add(buttonTwo).click(...);
Sign up to request clarification or add additional context in comments.

9 Comments

FYI combined selector is approximately 42% faster than add Source: jsperf.com/selector-vs-add/5
Agreed, but what if the selectors aren't available to be combined?
He already has both elements cached, how does that affect the outcome of the jsperf, assuming that the cached selections aren't used but have already been made?
Based on the fact that his only usage of the objects is in the event declaration in the given code, arguably it's overhead that he's got those variables in the first place. That's unless he has omitted code that uses said variables of course.
Plus if he did use them, arguably using $("#" + buttonOne.attr("id") + ", " + "#" + buttonTwo.attr("id")) would still be faster than add
|
5

Try combining the selector?

$("#buttonOne, #buttonTwo").click(...

Although you should really use on (jQuery 1.7) or delegate for pre-1.7, this will create the one event for all elements in the handler. Something like:

$(document).on("click", "#buttonOne, #buttonTwo", function () {
    //function here
});

on documentation: http://api.jquery.com/on/

delegate documentation: http://api.jquery.com/delegate/

9 Comments

I wouldn't use "delegated" events for this. They are "live" events, which I don't think is really needed here. $("#buttonOne, #buttonTwo").click is the way to go.
Well with the delegate you'll only have 1 event, with the click you'll have one for each element wouldn't you? :)
@mattytommo true, however any time you click anywhere in the document it's going to have to check the event.target against those two ids.
@KevinB Arguably a better overhead than having duplicate events though? :)
i'm leaning towards just using two selectors ($("#buttonOne, #buttonTwo").click(...), but is there a benefit to first assigning the selectors to a variable vs. directly using the selectors for .click()?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.