Danny Garcia
Danny Garcia

Reputation: 841

Should I store $(document).height() and/or $(window).height() as variables?

Is it a good idea to store these values as variables (outside of .scroll() ) in the following example?

$(window).scroll(function(){
  if ( $(document).height() <= ( $(window).height() + $(window).scrollTop() ) ) {
    // position stuff
  } else {
    // other position stuff
  }
});

The only downside to this I see is that the heights should be checked again in case of a window resize. Or do I only need to store the objects themselves?

Any feedback is greatly appreciated!

Upvotes: 2

Views: 1263

Answers (4)

Hussein
Hussein

Reputation: 42818

Every-time you wrap an Element with jQuery you are creating a jQuery object. If you plan to use that same jQuery object many times, then caching it is a wise thing to do. This is done by storing it in a variable and just call the variable everytime you want to use it. This will not longer create a jQuery object, but rather use the cached version.

Ex:

var wh = $(window).height();

Upvotes: 0

typeof
typeof

Reputation: 5932

Store $(document) and $(window), but re-check the height() and scrollTop() as this can change based on user interaction.

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359966

At the very least, it's definitely a good idea to store references to $(document) and $(window) outside of the scroll callback, since the scroll event might be fired repeatedly and rapidly.

var $win = $(window),
    $doc = $(document);

$win.scroll(function(){
  if ( $doc.height() <= ( $win.height() + $win.scrollTop() ) ) {
    // position stuff
  } else {
    // other position stuff
  }
});

It shouldn't hurt to do as you ask, and store the document and window heights outside of the callback as well — provided that you update them as needed. A nice way to handle all of this is to use the excellent jQuery throttle/debounce plugin, which gives you a simple interface for making sure a function doesn't run too frequently.

Upvotes: 6

Naftali
Naftali

Reputation: 146310

i do the same thing but i add on something else:

$(window).scroll(function(){
  if ( $(document).height() <= ( $(window).height() + $(window).scrollTop() ) ) {
    // position stuff
  } else {
    // other position stuff
  }
}).resize(function(){$(this).scroll()});//will call the scroll method on resize

or what you can do is this:

function pageSizer(){
      if ( $(document).height() <= ( $(window).height() + $(window).scrollTop() ) ) {
        // position stuff
      } else {
        // other position stuff
      }
}

$(window).scroll(pageSizer).resize(pageSizer);

Upvotes: 1

Related Questions