Search code examples
jqueryhtmlcsspositioning

Is there any way to make a fixed position element stop moving after the window is resized a certain amount?


I have a navigation bar that is fixed-position to the right side of the window. However, I want it to stop moving if the window is resized smaller than a certain size, and then reattach itself to the right side if the window is resized larger than this size.

I am trying to use jquery and $(window).resize and am able to stop the element from moving inwards after a certain point, but it does not reattach if the window is scaled larger.

Also, the effect is not very fluid and is rather jarring.

Any other solutions or ideas would be greatly appreciated!

http://jsbin.com/azanif/5

$(window).resize(function(){
  var windowWidth = $(window).width();
  if (windowWidth < 1200) {
    $('#test').css('left', '1100px');
  }
  else {
    $('#test').css('right', '55px');
  }
});

Solution

  • It keeps both distances, left and right once you've assigned them.
    Set left to auto when you set the right distance and it should work

     if (windowWidth < 1200) {
        $('#test').css('left', '1100px');
      }
      else {
        $('#test').css('right', '55px');
        $('#test').css('left', 'auto');
      }
    

    EDIT (Addition by anonymous user.)

    Stratton is completely right, you assign a value to "left" and never reassign it to auto. if you do it on else statement, you will have it working. Try with this code, and you'll have an effect like it's only moving passed some point.

    $(window).resize(function(){
      var windowWidth = $(window).width();
      $("#test").html(windowWidth);//Just to see in real time what's the window with
      if (windowWidth < 1200) {
        $('#test').css('left', '1020px');
      }
      else {
        $('#test').css('right', '50px');
        $('#test').css('left', 'auto');
      }
    });
    

    About performance, depends a lot of the computer and browser you use, for example on chrome in my computer looks great, but not in opera. That could be because (for example) Opera fires the event only when you stop resizing it (this article explains it a little bit).