Vaughn D. Taylor
Vaughn D. Taylor

Reputation: 61

$(window).load OR $(window).scroll in the same function?

I have implemented stickyfloat (http://plugins.jquery.com/files/stickyfloat_0.htm) on a site. It works great with one gotcha. The function triggers on $(window).scroll and not on $(window).load. I want it to trigger on either because I am linking to anchor points in the page (http://tre-stage.wdogsystems.com:8000/faq/#does-the-sale-of-my-receivables-have-a-negative-effect-on-my-credit-report) and I would like the side menu to appear when the page loads and not just when I initiate a scroll.

If you look at the page above, it's working just as I want it to. However, this is only because I've repeated the same function with a $(window).load. This seems highly inefficient to me. So, is there a way to chain the two together?

For example:

$(window).scroll || $(window).load (function () ...

Upvotes: 4

Views: 4757

Answers (4)

JPPP
JPPP

Reputation: 61

Why don't you just trigger a window scroll event on load? You could namespace your scroll event too to isolate it and have better access to it later...

$(window)
   .on('scroll.myscroll', function () {
      // do something on scroll event
   })
   .trigger('scroll.myscroll'); // trigger scroll event on pageload

But if you were actually wanting to run it on window load (ensuring the DOM is fully loaded incl. images etc) then the other examples mentioned are fine. But use the .on() method, rather than .bind().

$(window).on('scroll.myscroll load.myload', function () {
   // do something on scroll and load events
});

Upvotes: 0

SLaks
SLaks

Reputation: 887767

Like this:

$(document).bind('ready load scroll', function() { ... });

Upvotes: 2

Kris Ivanov
Kris Ivanov

Reputation: 10598

just chain in the bind, like:

$(window).bind("scroll load", ...)

however it is very bad idea to attach to scroll event

a very good explanation why and a great solution: http://ejohn.org/blog/learning-from-twitter/

Upvotes: 3

jAndy
jAndy

Reputation: 236092

jQuery's .bind()help method allows multiple events bound at once.

$(window).bind('scroll load', function() {
    // code here triggers for both, scroll & load events
});

Upvotes: 3

Related Questions