3

I'm trying to use javascript/jQuery to find the width of the window and use the variable in a later function.

$(function resizer() {

    function doneResizing() {
        var windowWidth = $(window).width();
        return windowWidth;
    }
    var getWidth = doneResizing();


    var id;
    $(window).resize(function() {
        clearTimeout(id);
        id = setTimeout(doneResizing, 0);
    });
    doneResizing();


    return getWidth;
});
var finalWidth = resizer()

So the resize function updates whenever the window is resized and windowWidth is updated automatically. When the variable is returned outside of the function, getWidth doesn't update with a window resize unless I refresh the page. Any ideas? I just picked up js/jq 2 weeks ago, and I'm doing my best to wrap my head around returns and closures, so I may have overlooked something here. Thanks.

cat-t
  • 1,346
  • 1
  • 18
  • 34
  • I've figured out why your code only worked on reload. On reload, `var getWidth = doneResizing();` is executed, and `return getWidth` is executed leading up to `finalWidth` being assigned. However, after that whenever the window is resized, `setTimeout(doneResizing, 0);` is called. `setTimeout` does nothing with the returned value from `doneResizing()`. – Menelaos Sep 19 '13 at 10:02

2 Answers2

2

You have mixed up your resizer function with the jQuery ready function. To keep track on the window width you can do

(function ($) {
    var windowWidth;
    // when the document is fully loaded
    $(function(){
        // add an resize-event listener to the window
        $(window).resize(function(){
            // that updates the variable windowWidth
            windowWidth = $(window).width();
        })
        // trigger a resize to initialize windowWidth
        .trigger('resize');

        // use windowWidth here.
        // will be updated on window resize.
    });

}(jQuery));
jukempff
  • 965
  • 6
  • 12
2

it would be much simpler to do the following:

var finalWidth;

$( document ).ready(function() {
      //Set this the first time
      finalWidth = $(window).width();       

      $(window).resize(function() {
      //resize just happened, pixels changed
       finalWidth = $(window).width();

        alert(finalWidth); //and whatever else you want to do
        anotherFunction(finalWidth); 
    });
 });

and use finalwidth outside as it is a global variable. You get the same functionality without the complexity.

Update

As commented, global variables are bad practice ( e.g. also http://dev.opera.com/articles/view/javascript-best-practices/ ).

To avoid a global variable finalWidth can be moved inside document.ready and any necessary functions can be called from inside resize(function() { event handler.

Update 2

Due to the problem with dragging causing multiple resize events, code has been updated.

Reference: JQuery: How to call RESIZE event only once it's FINISHED resizing?

JSFiddle: http://jsfiddle.net/8ATyz/1/

$( document ).ready(function() {
      var resizeTimeout;

      $(window).resize(function() {
        clearTimeout(resizeTimeout);
        resizeTimeout= setTimeout(doneResizing, 500);      
     });

      doneResizing(); //trigger resize handling code for initialization 
 });


function doneResizing()
{
    //resize just happened, pixels changed
    finalWidth = $(window).width();

    alert(finalWidth); //and whatever else you want to do
    anotherFunction(finalWidth);    

}

function anotherFunction(finalWidth)
{
    alert("This is anotherFunction:"+finalWidth);   
}
Community
  • 1
  • 1
Menelaos
  • 23,508
  • 18
  • 90
  • 155
  • 2
    Also, make sure to wrap it in your $(document).ready function. – BenM Sep 19 '13 at 09:23
  • 1
    You should not encourage people to use globals for that kind of stuff. Those things should always be in their own scope. – jukempff Sep 19 '13 at 09:25
  • True, he can move finalWidth inside ready and call any function he wants by passing the variable. Thanks! – Menelaos Sep 19 '13 at 09:29
  • I just tried out your solution, and I can now use the variable in other functions. But the only problem is that it doesn't update dynamically when I resize the window, only when I refresh. Do you know how I would be able to do that? – cat-t Sep 19 '13 at 09:42
  • 1
    @cat-t I've updated the code and included a link to a JSFiddle. I had overlooked why you have the timeout. It's better to assign `finalWidth` within the `doneResizing()` function, and pass it from there. http://jsfiddle.net/8ATyz/1/ . In the JSFiddle the alerts are fired whenever the window is resized. – Menelaos Sep 19 '13 at 09:47
  • @cat-t The main difference I see from your original code, is that you should call your remaining functions from inside `doneResizing()` and pass the `windowWidth` variable. Your problem in the original code was that you return the width from `downResizing()`... but when a resize occurs `setTimeout(doneResizing, 0);` is called...and the returned value is not used anywhere. Only when you reload the first is the value used. – Menelaos Sep 19 '13 at 10:00