0

I know that puting reference of HTML element into the variable is a good practice if I need to reference to this element many times. But I run into the problem with this while making my project. How can I bind multiple and the same events to the elements which are stored into the variable?

For now I deal with it this way:

var producerEl = $("#js-producer");
var brandEl = $("#js-brand");
var seriesEl = $("#js-series");

bind(seriesEl);
bind(brandEl);
bind(seriesEl);

function bind($el) {
    $el.on("keypress", function () {
       // some code..
    });
}

I need something like $(producerEl, brandEl, seriesEl).on...

3 Answers 3

1
var producerEl = $("#js-producer");
var brandEl = $("#js-brand");
var seriesEl = $("#js-series");

  producerEl.add(brandEl).add(seriesEl).on("click", function () {
        alert('hello');
    });
Sign up to request clarification or add additional context in comments.

Comments

0

If you are trying to keep your code readable, might I suggest this approach?

$("#js-producer, #js-brand, #js-series").on('keypress', function () { });

3 Comments

No. I want use references I have in variables and don't find it second time (performance!).
Your approach doesn't improve performance one bit. It's purely for readability.
jQuery has a cache system built it so I believe once queried even if you use the CSS selector again it will be fine.
0

Hmm. If you're using these selectors only one, don't care about "I know it is good to". The best solution is the one provided by David Smith.

Anyway, jQuery is using the sizzle selector engine, who has it's own cache. You can ask for $("#js-producer, #js-brand, #js-series")

the result would be cached and reused.

1 Comment

The question is just a exmaple. I use these selectors many times.

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.