- This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
Viewing 2 posts - 1 through 2 (of 2 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › [Solved] Best way to reference object variable?
Of the following two examples, which is the best way to reference an object variable within jQuery? I’m thinking the first example is correct. I’m pretty sure the second example causes the jQuery object to be referenced twice. Am I on the right track? Is there a difference between the two?
First
$(function() {
var root = $('html,body');
var someClass = $('.someClass');
root.fadeIn(600);
someClass.fadeIn(600);
});
Second
$(function() {
var root = $('html,body');
var someClass = $('.someClass');
$(root).fadeIn(600);
$(someClass).fadeIn(600);
});
ALSO
Is it better to define jQuery object variables with the $ in front to differ from string variables? For example…
var $root = $('html, body');
var $someClass = $('.someClass');
var offsetTop = $('.anotherClass').offset().top;
You are correct, the second example does that. You only need to reference the jQuery object once per variable. It is common practice to name jQuery referenced variables with ‘$’ in front of them, just to remind you that they inherit from the jQuery object and you can use methods like .each, .after.. etc. on them. This also would prevent you from doing something like
div = $('div.someClass');
// 200 lines of code
$(div). some jQuery method