1

How would you change an elements css position to fixed without resetting the current scroll position?

Using script to change position:

$('.bigwidth').click(function() { 
     $(this).css('position','fixed');    
})

this example: http://jsfiddle.net/7gRZJ
if you scroll the element, then click on the element, it will change it to fixed and reset scroll position..

The desired behavior is to change it to fixed while retaining the current scroll position.

4 Answers 4

3

Adding "return false" inside the click function will prevent the default behavior of jumping you back to the top of the page / resetting the scroll position.

Updated code:

$('.bigwidth').click(function() { 
     $(this).css('position','fixed');
     return false;    
})
Sign up to request clarification or add additional context in comments.

1 Comment

This is a much simpler solution than any other option. It worked perfectly.
2
$('.bigwidth').click(function() { 
     $(this).css({
          position :'fixed',
          left : -(document.body.scrollLeft)
    });
});

Comments

2

Since the positioning of the element turns to fixed, this means that it effectively gets taken out of the layout of the page. This means that the body would cease being expanded to its width the moment its position attribute was changed, so it jumps back to the left. One way to solve this is to reposition the element to simulate the previous scroll position after changing its position attribute. So your script could look something like:

$('.bigwidth').click(function() {
     var scrolled = $(document).scrollLeft();
     $(this).css('position','fixed');
     $(this).css("left", -scrolled);
});

Here's an example of this working.

Comments

0

If the scroll is reset automatically, you could reset it after click event. Get the actual position of the scroll -> change position to fixed and reset scroll with the previous position. Use .scrollTop() method to achieve it --- jquery

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.