Reputation: 10282
Let me start by saying that I'm not a JavaScript programer or a jQuery guru by any means, I'm actually just starting with jQuery.
I have the two following jQuery codes:
$('.tipTrigger').hover(function(){
$(this).toggleClass('active').prev('.tipText').stop(true, true).fadeToggle('fast');
});
and
if ($(".tooltip-container").length > 0){
$('.tipTrigger').hover(function(){
$(this).toggleClass('active').prev('.tipText').stop(true, true).fadeToggle('fast');
});
}
Several questions I have about this:
if ($(".tooltip-container").length > 0){
?if
?Any other comments/help with this simple comparison would be greatly appreciated.
Thanks in advance.
Upvotes: 0
Views: 102
Reputation: 22580
What is basically the difference between the two codes above?
The second will only set the hover function if there is an element on the page with the class 'tooltip-container'
What is the meaning of if '($(".tooltip-container").length > 0){'?
Simple if statement to test if element having class
tooltip-container
exist on document
Is there a benefit to using the above if
?
In short, in this case, not really, since the .hover wont be asigned unless an element having class
tipTrigger
exist anyway. Also this could cause performance issues since it only checks to see if onetooltip-container
element exist. If this is a check to ensuretipTrigger
is "inside" said container, it will fail in that as soon as one element withtooltip-container
is found, ALL elements withtipTrigger
will be asigned hover function and this MAY BE undesired.
What's more 'efficient' from a developer's stand point? (that is IF something so small would have a considerable performance impact in any way)
If you must check to make sure that only
tipTrigger
elements insidetooltip-container
elements are fired, you might consider use of jQuery's .each function or use CSS in the selector, as follows
>
$('.tooltip-container .tipTrigger').hover(function(){
$(this).toggleClass('active').prev('.tipText').stop(true, true).fadeToggle('fast');
});
tipText
that comes before current element in domUpvotes: 1
Reputation: 72930
Upvotes: 4
Reputation: 160321
The second sets the hover function only if there are one or more DOM elements with the class "tooltip-container"
.
Both traverse the DOM to find elements with the specified class(es); whether or not the difference in efficiency is worth it depends on the DOM, when the statement is called, etc.
Upvotes: 4