Reputation: 31156
I have a global flag variable. If this flag's value is true
then I add a lot of <div>
s to the DOM, otherwise nothing happens. After this I need to handle the click event on all of the previously added <div>
s. I can't add the click handler immediately after I created the <div>
s, because they are in different parts of the code, however the flag variable is still accessible. I add the click handlers this way:
$('.js-click').click(function() {
//Handle the click.
});
It doesn't matters if the <div>
s were added previously or not, the code above will work in any case, however because I have the global flag variable, I could add a condition before the jQuery code, so it would execute only if the <div>
s were created.
if(flag) {
$('.js-click').click(function() {
//Handle the click.
});
}
Does this makes any difference? Is there an amount of element or a type of jQuery selection where this condition would increase efficiency?
Upvotes: 0
Views: 55
Reputation: 8781
+1 for epascarello's Event bubbling solution.
There are also couple of nice articles about JQuery performance rules i find helpful:
10 Ways to Instantly Increase Your jQuery Performance
Upvotes: 0
Reputation: 1321
Quick answer would be: if the actual selector execution (which is typically very fast) is not a problem for you, then no flag testing is needed.
If a performance might be a problem, then adding the flag test will definitely help (but it will increase the interdependence of your code, so in case you rename the flag or change the logic related to it, this code might stop working which can stay unnoticed).
Upvotes: 1
Reputation: 207537
Why don't you just use event bubbling and do not worry about when they are added?
$(document /*or a container element that holds them all*/).on("click", ".js-click", function() {
//handle the click
});
Bonus of this is you are not adding a click event to multiple elements, once and done.
Upvotes: 4