Update div position on window resize

Hi there,

I’m trying to change the position of a div as the window is resized using jQuery.

Here’s my code:


$(window).resize(function(){
  newWinWidth = $(window).width();
  $('#slider').width(newWinWidth*4);
  var pos = $('#slider').position();
  var page = Math.floor(Math.abs(pos.left)/winWidth);
  var offset = winWidth - newWinWidth;
  var leftPos = pos.left + (offset * page) + 'px';
  $('#slider').css({left: leftPos});
});

So when I resize the window, #slider doesn’t move. If I put a fixed number into the code on the last line, it works fine.

Can anyone shed any light on the best way to approach this problem?

Many thanks in advance,
Mike

It’s this line:


var page = Math.floor(Math.abs(pos.left)/winWidth);

You’re using a variable called winWidth, which hasn’t been defined. I think you mean to use newWinWidth?

Hey Immerse, thanks for your reply.

winWidth is defined earlier in my code, I just included a snippet here for simplicity. I didn’t notice that the variable was missing when I put up the original post.

There’s a test page here:
Into the Green Design

with the complete code. I’ve put a console log on leftPos, so you can see the output of that variable. Everything seems to be working fine, up until the css method.

A-ha!

So actually it was working the whole time.

Here’s a slightly larger snippet of code:


$(document).ready(function(){
  var winWidth = $(window).width();
  $(window).resize(function(){
    newWinWidth = $(window).width();
    $('#slider').width(newWinWidth*4);
    var pos = $('#slider').position();
    var page = Math.floor(Math.abs(pos.left)/winWidth);
    var offset = winWidth - newWinWidth;
    var leftPos = pos.left + (offset * page) + 'px';
    $('#slider').css({left: leftPos});
    [B]winWidth = newWinWidth;[/B]
  });
  $('#slider').width(winWidth*4);
});

The highlighted line is what I just added, and now it works fine.

winWidth is set on document ready, and is used to find the difference between the original window size, and the new window size. Because I wasn’t updating that variable leftPos was always the same number. So the div did move, just very slightly at the start, and then remained still.

I love it when a plan comes together…