Johnny
Johnny

Reputation: 9964

Is it good practice to call a function multiple times in jQuery?

I have this code where I need to call a function multiple times.

    $(window).resize(function() {
    centerBox();
}); 

$(window).scroll(function() {
    centerBox();
}); 

centerBox();

And I realise this is incredibly messy. Is there any better way to write this?

Upvotes: 1

Views: 948

Answers (4)

Alex K.
Alex K.

Reputation: 175876

You could bind + call;

$(window).on("scroll resize", centerBox).scroll();

Upvotes: 2

Jon
Jon

Reputation: 437574

I don't think it's messy; it describes exactly what you want to do. That said, you could shorten it down to:

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

and further to

$(window).resize(centerBox).scroll(centerBox).trigger('resize');

and even further to

$(window).on("resize scroll", centerBox).trigger('resize');

since .on supports binding to multiple events if their names are space-separated.

Upvotes: 3

lumio
lumio

Reputation: 7585

You can shrink your code to 3 lines:

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

And of course you have to define your function on top

Or you also can use it in 2 lines by combining it, but that would also be a little messy:

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

Upvotes: 5

silly
silly

Reputation: 7887

var f = function() {
    centerBox();
};

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

Upvotes: 4

Related Questions