Utilizing a fresh stance when transitioning to a stable position

How can I make an element on my page scroll with the page until a certain point, and then switch to fixed position when another moving element interacts with it? The issue I'm facing is that when it switches to fixed position, it jumps down to its original position on the page. Is there a way to maintain its position when it becomes fixed instead of jumping back?

Here's the code snippet:

jQuery(window).scroll(function (event) {
     var top = jQuery("accordion").offset().top - parseFloat(jQuery("#accordion").css("marginTop").replace(/auto/, 0));
     // determine the y position of the scroll
     var y = jQuery( "#navigation" ).offset().top + jQuery( "#navigation" ).height();

     if (y >= top) {
         // add the fixed class if necessary
         jQuery("#accordion").css('position','fixed');
     } else {
         // remove the fixed class if not needed
         jQuery("#options_accordion").css('position', '');
     }
});

Answer №1

Adjusting the top position of your sticky element when switching it to position: fixed is crucial. I have put together a simple example to illustrate this concept:

http://jsfiddle.net/7jfRQ/

var $sticky = $('.sticky-element');
var $window = $(window);
var originalPosition = $sticky.offset().top;

// Modify this value if you want the switch to occur at a different point
var switchPosition = 50;

$window.on('scroll', function(event) {
    var scrollDistance = $window.scrollTop();

    if ((originalPosition - scrollDistance) <= switchPosition) {
        if (!$sticky.hasClass('fixed')) {
            $sticky.css('top', switchPosition);
            $sticky.css('left', $sticky.offset().left);
            $sticky.addClass('fixed');
        }
    } else {
        if ($sticky.hasClass('fixed')) {
            $sticky.removeClass('fixed');
        }
    }
});

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

Difficulty arranging objects in both horizontal and vertical orientation within a single flexbox container

I'm struggling with aligning my bootstrap flexbox container properly. I want the image to remain horizontal on the left, while the title, description, and "powered by" sections stack vertically to its right. So far, all my attempts to achieve this hav ...

Whenever I press a button, my card holder gradually slides downwards

I'm facing an issue with my code and I'm unsure whether it's related to CSS or JavaScript. Whenever I click the button on my page, my card-container2 moves downward unexpectedly. Here is the snippet of my code: HTML: <div class="car ...

Developing a JSONP functionality

I am currently trying to use JSONP in order to display data within my div. However, the code is not showing anything. I have also included jquery.jsonp.js in my project with the following path: PRJFOLDER->WEBPages->JavaScript->qu ...

Issue with background in list items

I am struggling with aligning the background of my vertical menu to the right and center from the top. Here is the code I have tried: ul.nav { margin:0; background-position:center; background-image: url(../images/nav_bg.gif);font-family: "Century Go ...

How to effectively utilize the combination of select and JavaScript?

I am in the process of implementing a selection feature that allows users to choose between two options: owner or non-owner. Depending on their choice, I want to present them with different sets of questions and allow them to input numerical answers from ...

The Quickest Way to Retrieve Attribute Values in JavaScript

I'm trying to access a specific attribute called "data-price". Any tips on how I can retrieve the value of this attribute using this syntax: Preferred Syntax div[0].id: 48ms // appears to be the quickest method Alternative Syntax - Less Efficient ...

Arrangement of HTML Form in Rows

I am currently working on setting up an HTML form that necessitates a layout with up to 4 distinct rows. Please refer to the code below along with some notes. Essentially, I want the first 3 form items to be on row 1, the next 3 on row 2, and so forth. Eac ...

The VisJS Network lacks proper alignment

I am attempting to generate a vis js network. This is how I envision the graph should appear https://i.sstatic.net/xIv3s.png Here is the code snippet extracted from the page source <script type="text/javascript"> var options = { ...

SwitchClass or AppendClass are not compatible with input tags

I am having trouble changing the border color of an input element using jQuery. Here is the setup: <input id="box" type="text" /> And the CSS class I am trying to toggle: .box-change { border-color:#ffffff; } Below is the jQuery code I am usi ...

When a td element is clicked, the Textbox will also be clicked

Similar Question: Dealing with jQuery on() when clicking a div but not its child $(oTrPlanning).prev().children('td').each(function () { this.onclick = setCountClick; }); When a TD element is clicked, the function setCountClick() i ...

PHP class initialization leads to 500 Internal Server Error

Currently, I am developing a database system to enhance our client management processes. The logic for displaying client data is functioning perfectly. The designated class responsible for handling method calls is named "kunde." Here is how I initialize ...

What is the relationship between html, body, and window when scrolling through code?

I've been working on adding a scroll-to-top button to my website. After doing some research online, I came across this code snippet: $('html, body').animate({scrollTop:0}, 'slow'); It's interesting that they are trying to scr ...

Having trouble applying custom CSS styles to images in CarouselItem using Reactstrap? Learn how to use a div instead of an image for a solution

Currently, I am utilizing reactstrap in my live website powered by react.js. I am seeking assistance on how to implement the reactstrap carousel. Specifically, I am struggling with applying CSS directly to the image within CarouselItem. Since there is a s ...

"Enhancing User Interaction with jQuery Hover State Dropdown Menus

Here's my issue: I've created a drop-down menu and I want the text color to change when hovering over the menu. Additionally, I'd like the hover state to remain active when hovering over the submenu. Currently, I'm using this code: $( ...

How much space should be left from the edge for jQuery UI dialog to be

Typically, a dialog is centered using the following code: $(el).dialog('option', 'position', 'center'); Is there a method to specify a "minimum" distance from the side? For example, ensuring that the top position is always a ...

I am interested in duplicating code, but I am unfamiliar with the concept of using loops

Can someone assist with this issue I'm facing? Here is the code snippet: function change_color(color) { $("body").animate({ backgroundColor:color }, '1000'); } setTimeout(function () { change_color('#4AC900' ); }, 500); ...

Achieve full width for container using flexbox styling

In an attempt to develop a category dropdown menu with multiple columns based on the length of the <ul>, I am facing some challenges. For reference, you can view the fiddle that I have created here. The goal is to arrange each submenu item below th ...

Are there specific elements that fall under the umbrella of CSS?

Code is causing some red boxes to appear unexpectedly. User agent: Chrome/80.0.3987.149 Linux x86_64 Here is the code snippet: <html lang="en"> <head> <meta charset="utf-8"> <title>Flow</title> ...

Discover the CSS styles that Bootstrap has implemented on this element

My footer and logo look great without bootstrap, but when I add it in, everything gets messed up. I'm not sure what styles bootstrap is applying to the elements, making it difficult to troubleshoot. I know I can override the styles, but I need to firs ...

I'm stumped by this code; I can't figure out what's going wrong

$(document).ready(function() { $.ajax({ type: 'GET', url: 'data.json', dataType: 'json', success: jsonParser }); }); $(".btn_val1").click(function() { ...