How can I call a function multiple times?

My issue is: I'm developing a mobile-friendly website with 2 stylesheets, one for the "PC-oriented" visualization and the other for the mobile visualization. Along with the 2 CSS, I need a function to modify some href attributes on the menu when switching from one visualization mode to the other.

I'm not going deep into the details of the stuff as it would be very long and probably boring, anyway I need the function to be called both on $(document).ready AND on $(window).resize, that is every time the window is resized.

So I declared a function and named it goToAnchor in order to be able to call it more than once:

$(document).ready(function() {
   function goToAnchor() {  ... modify some href attr ... }
   goToAnchor();
});

That's perfectly fine, but as I said I also need the function to be executed every time the window is resized, so I thought the code might look like:

$(document).ready(function() {
   function goToAnchor() {  ... modify some href attr ... }
   goToAnchor();
   $(window).resize(goToAnchor());
});

The problem is simple, the function doesn't run on resize. I checked the jQuery documentation and noticed that every example regarding linking a function to an event is written like this:

$(window).resize(function() { ...do stuff...} );

I wouldn't resort using an anonymous function though, as I have already written the function previously. What I want to do is extremely simple: to call a function multiple times without resorting to anonymous functions to "duplicate" my code (after all, that's how functions are supposed to work, right?).

Answers:

Answer

Change $(window).resize(goToAnchor()); to $(window).resize(goToAnchor);

Answer

You want to replace: $(window).resize(goToAnchor()); with $(window).resize(goToAnchor);.

Your code is passing the response of the goToAnchor function and what you want to do is pass a reference to the function, which we do by omitting the parenthesis.

But you could also do this:

$(function() {
   $(window).bind('resize', function () { /*resize code*/ }).trigger('resize');
});

This effectively runs the code when the resize event fires on the window object as well as on document.ready (.trigger('resize') makes the resize event fire on document.ready).

Answer

A good way to see what is happening, is by changing the declaration of the function to:

var goToAnchor = function() { ... modify some href attr ... }

In which case

$(window).resize(goToAnchor);

and

$(window).resize(function() { ... modify some href attr ... });

are clearly doing the same thing.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.