Set the CSS position to fixed without having to reset the scroll position

What is the best way to change an element's CSS position to fixed without losing the current scroll position?

Here is a method using JavaScript:

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

For example, visit this link: http://jsfiddle.net/7gRZJ
If you try scrolling the element and then clicking on it, it will change to a fixed position and reset the scroll. This behavior can be improved by retaining the current scroll position when changing to a fixed position.

Answer №1

By including "return false" within the click function, you can stop the default action of being taken back to the top of the page or resetting the scroll position.

Here is the revised code snippet:

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

Answer №2

$('.bigwidth').click(() => { 
     $(this).css({
          position :'fixed',
          left : -(document.body.scrollLeft)
    });
});

Answer №3

When the element's position changes to fixed, it is essentially removed from the page layout, causing the body to no longer expand to its width. As a result, the element may jump back to the left. One solution is to reposition the element to mimic the previous scroll position after changing its position attribute. You can achieve this by incorporating the following script:

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

Check out this example for a demonstration.

Answer №4

To automatically reset the scroll, you can implement a click event that resets it. Retrieve the current scroll position, set it to fixed, and then reset the scroll to its previous position using the .scrollTop() method --- jquery

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Increasing the size of the td element when including a new row

Here is an html page example that I am working with: However, when I add a new row beneath the existing row that contains a div block and form within it, I notice that the td tag in the first row expands in width, as depicted in the image below. Below is ...

jQuery .click() only triggering upon page load

I've been searching all over the place and I just can't seem to find a solution to my specific situation. But here's what I'm dealing with: Instead of using inline HTML onclick, I'm trying to use jQuery click() like this $(docume ...

DOM is set for Jquery activation

I'm dealing with an issue in JQuery that I recently started working on. I have a large HTML page with a widget at the beginning, but when I use document.ready, it waits for the entire page to load before executing, which takes too long. Is there a wa ...

Is there a way to prevent a sticky div from covering the footer?

I recently took some code from a blog and added it to my fiddle account. Initially, everything was working smoothly. However, as I started adding text boxes by clicking the “Add” button multiple times, I encountered a problem. The yellow bar that stick ...

What is the process for embedding images and text within a nested division element?

I have a website layout with 4 main sections: header, left side, right side, and footer. I would like to further divide the header into two sections - left header and right header. The right header should contain an image along with other options like home ...

Trigger the click() event in jQuery before the blur() event

Looking to implement autocomplete suggestions in an input field? Take a look at the code below: <input type="text" id="myinput"> <div id="myresults"></div> To hide the results' div on the input's blur event, you can use this c ...

Using Javascript and CSS to Float DIV Elements

Recently, I've been working on a small algorithm that adds a special class to an element when the mouse reaches the halfway point or beyond on the X-axis of the browser. I also have a screenshot that demonstrates where this application will be utiliz ...

After diligently following every step on OneCheckout and getting no response when placing an order, I decided to upgrade my Magento version from 1.6.1.0 to 1.8

After upgrading the Magento version from 1.6.1.0 to 1.8.0, everything seems to be working smoothly. However, customers are facing an issue during checkout where they can't actually place their order. Despite following all the steps correctly, when t ...

Discovering the art of integrating RSS feed with GAE database

Is there any game library that can accomplish this task? I believe jQuery may also be able to achieve this, is that correct? Thank you ...

Looking to display or conceal a text box with a date picker based on the selection of a specific value from a drop-down menu

I have a dropdown with two options: Indian and Others. When I select Others, I want to display three textboxes - two with date pickers and one with a simple text input field. I have tried writing the following HTML code but I am unable to get the date pick ...

Ensure that all images uploaded are adjusted to fit the consistent dimensions within a card

I am in the process of creating a form that allows users to upload various images, which will then be displayed as cards on a website. After uploading an image, the size of the card automatically adjusts to fit the image, ensuring that all cards maintain ...

Solving the Size Problem with Bootstrap 5 Off Canvas

I am utilizing the bootstrap 5 off-canvas feature for collapsing, while also having an announcement bar that appears as a dismissible alert on top of my navbar. The issue I'm facing is that the top size of my off-canvas is not adjusting properly whe ...

Dynamically modifying the styling of elements within an iframe

In my current project, I encountered a challenge with changing the background color to black and the body text color to white within an iframe. Additionally, all elements that are originally styled with black in an external stylesheet also need to be chang ...

Exploring the Power of Jquery UI Combobox and Dropdown Selection menus

I'm experiencing issues with Jquery UI Combobox and asp.net The DropDown is not functioning properly. Encountering a JavaScript error "Uncaught TypeError: Cannot set property '_renderItem' of undefined" 'input.data("ui-autocomplete"). ...

inputting an array of strings into the value attribute of an input element using jQuery

Whenever a user writes something in the input field with id="clientAdd" and presses enter, that text should be displayed as a tag inside a div. These tags are then saved as an array of strings, which I want to pass as the value for the hidden input field w ...

What could be the reason for the d-flex class in bootstraps preventing my div from expanding to 100% width?

I have a div where I need to display two elements next to each other: a search input field and the corresponding submit button. My attempt so far was to achieve this using the following code: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn. ...

Problems arising from the layout of the PrimeNG DataView component when used alongside Prime

I've been working with a PrimeNG DataView component that requires the use of PrimeFlex's flex grid CSS classes to set up the grid structure. One of their examples includes the following instructions: When in grid mode, the ng-template element ...

Determining the container height for every two-image row

I am currently working on a project for this website. My focus right now is on resizing vertical images using the following script: function Gallery(selector) { this.add_module = function (type, image) { var portrait_text = image.next('.portr ...

What are some ways to apply selector combinators to hashed CSS module classes?

Seeking advice on overriding a style in a CSS module for a third-party datepicker component used within a custom component. The challenge lies in targeting the correct element with a selector combinator, complicated by the dynamic creation of class names i ...

Storing jQuery output in a global variable can be achieved by assigning the result

Take a look at the Code snippet below - $(function() { $.fn.getPosition = function() { var results = $(this).position(); results.right = results.left + $(this).width(); results.bottom = results.top + $(this).height(); return results; } ...