0

I need to assign a dynamic value to a variable. Specifically, I would like to assign the window width and detect if window has been resized.

To assign window width I know it would be as follows:

var windowWidth = $(window).width();

But I dont't know how to get window width when it has been resized, so that variable would always have the current window width.

Is that possible? I can't find the way to do that!

Than you very much in advanced!

Jur.

1
  • add a resize event on the window or body Commented Nov 23, 2012 at 14:50

3 Answers 3

1
$(window).on('resize', function() {
    var w = $(window).width();
});

DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

If you're doing this to check when the window has been resized, why not add an event handler to the window resize event?

$(window).resize(function() {
    alert("resized");
});

If you only want the function to run once when the resizing has finished, try this:

var resizeTimer;
var windowWidth;
$(window).resize(function() {
   clearTimeout(resizeTimer);
   resizeTimer = setTimeout(function() {
       windowWidth = $(window).width();
       alert("New width: " + windowWidth);
   }, 1000);
});

4 Comments

Thanks! But what i need is to run the variable out from de .resize function, to be a global variable, is that possible?
Yes. Declare var WindowWidth; at the top of the page (outside the resize event) then set it on the event fire.
@user1722662 No problem, I've just updated my answer. Thanks webnoob
And how would I do that? What I am doing is moving left position of a div based on window width and if I resize the window the width variable doesnt change so the left position is not the right one.
0

You can use this event:

window.onresize = function(event) {
    windowWidth = $(window).width();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.