Jake Hills
Jake Hills

Reputation: 448

On Load, On Resize and On Scroll - what's the best way to run separate functions?

On Load, On Resize and On Scroll - what's the best way to run separate functions?

I have a few functions, all do different parts throughout the website. Some for a parallax effect, some for a gallery etc..

At the moment I am grouping them in 3 separate 'on..' functions (as below). It works, but I'm sure there's a better way?

$(document).ready(function () {

  // on load functions go here

  $(window).on("load resize", function () {
    // on load and on resize functions go here
  });

  $(window).on("load resize scroll", function () {
    // on load, resize and scroll functions go here
  });

});

Upvotes: 0

Views: 923

Answers (2)

Jake Hills
Jake Hills

Reputation: 448

After the suggestions here and continuing my search, the best solution seems to be:

function load() {
});

function loadResize() {
});

function loadResizeScroll() {
});

$(window)
  .on('load', load)
  .on('load resize', loadResize)
  .on('load resize scroll', loadResizeScroll);

Upvotes: 0

John Grant
John Grant

Reputation: 82

Try

$(document).ready(myFunction1);

myFunction1 () {

  // on load functions go here

  $(window).on("load resize", myFunction1);

  $(window).on("load resize scroll", myFunction2);

}

function myFunction2(){
// on load and on resize functions go here
};

function myFunction3(){
// on load, resize and scroll functions go here
};

Upvotes: 1

Related Questions