What is the best way to ensure the div stays in sync with scrolling?

Trying to synchronize two divs while scrolling. Essentially, I have a page scroll and want to fix the second div when it reaches the top.

Please refer to the gif icon attached for clarification.

You can view my progress so far here.

The current issue in my code is that both divs reach the top simultaneously as I scroll.

This is the jQuery code being used:

jQuery(document).on('ready', function() {
    "use strict";
    
    /* -------------------------------------
            Set Page Height
    -------------------------------------- */
    function headerFullScreen() {
        var _vph = jQuery(window).height();
        jQuery('#header').css({'height': _vph + 'px'});
    }

    function imgBoxFullscreen() {
        var _vph = jQuery(window).height();
        jQuery('#imgbox').css({'height': _vph + 'px'});
        
        jQuery(window).scroll(function(){
            if(jQuery(window).scrollTop() >= _vph - 68){
                jQuery('.navigationarea').addClass('ontop');
            }
        })
    }

    window.onresize = function() {
        headerFullScreen();
        imgBoxFullscreen();
    }

    var refreshId = setInterval(refresh, 500);

    function refresh() {
        headerFullScreen();
        imgBoxFullscreen();
    }

    /* -------------------------------------
            FIXED LOGO AND NAV
    -------------------------------------- */
    jQuery(window).scroll(function(){
        var scrollTop = 1;
        
        if(jQuery(window).scrollTop() >= scrollTop){
            jQuery('.logoholder, .navigationarea').css({
                position : 'fixed',
                top : '0',
                margin : '0'
            });

            jQuery('.navigationarea').addClass('ontop-mobile');
            jQuery('.navigationarea').addClass('ontop');
            jQuery('.menu_lis').addClass('top_menu');
            jQuery('.straight-menu').addClass('hide_bottom_menu');
        }else{
            jQuery('.navigationarea').removeClass('ontop-mobile');
            jQuery('.navigationarea').removeClass('ontop');
            jQuery('.menu_lis').removeClass('top_menu');
            jQuery('.straight-menu').removeClass('hide_bottom_menu');
        }

        if(jQuery(window).scrollTop() < scrollTop){
            jQuery('.logoholder').removeAttr('style');
            jQuery('.navigationarea').removeClass('ontop-mobile');
            jQuery('.navigationarea').removeClass('ontop');
            jQuery('.navigationarea').removeAttr('style');
        }
    })
});

I have also included a gif demonstrating how it is supposed to function.https://i.sstatic.net/i9zbT.gif

Answer №1

Here is a simplified version of the script that may be helpful for you.

$(window).scroll(function() {
  var scrollTop = $(this).scrollTop();
  if (scrollTop > 0) {
    $(".logo,.menu").css({
      position: 'fixed',
      top: '0',
      margin: '0'
    });
  } else {
    $(".logo,.menu").removeAttr('style');
  }
});

Check out the demo here

Answer №2

It seems that Dan accidentally omitted a crucial detail in his response. To achieve the desired effect, you should compare the initial position of the div element from the top of the page to the amount you have scrolled.

If the distance scrolled exceeds the initial offset, then you can set the element as sticky. Otherwise, revert it back to its original style.

You have the flexibility to apply styles using jQuery's .css() method like demonstrated below, or utilize class toggling, or a combination of both approaches, based on your preference.

For instance:

$(function() {
  var targetDiv = $('#section1').find('.section-container');
  var sec1offset = targetDiv.offset().top;

  $(document).scroll(function() {

    var distY = $(document).scrollTop();

    if (sec1offset <= distY) {
      $(targetDiv).css({
        position: 'fixed',
        top: '0',
        left: '10vw',
        zIndex: '0'
      });
    } else {
      $(targetDiv).css({
        position: '',
        top: '',
        left: '',
        zIndex: ''
      });
    }
  });

});
#section0 {
  background-color: midnightblue;
  width: 100%;
  height: 60vh;
}

#section1 {
  background-color: gold;
  width: 100%;
  height: 60vh;
}

#section1 .section-container {
  width: 80%;
  height: 30vh;
  position: relative;
  top: 20vh;
  left: 10vw;
  background-color: firebrick;
}

#section2 {
  background-color: midnightblue;
  width: 100%;
  height: 100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="section0"></section>
<section id="section1">
  <div class="section-container"></div>
</section>
<section id="section2"></section>

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

Problem with integration of Bootstrap datetime picker in AngularJS directives

I am currently utilizing the Bootstrap Datetime picker to display data from a JSON file in calendar format. The data is first converted into the correct date format before being shown on the calendar, with both a To date and From date available. scope.onH ...

Angular - Dividing Functionality into Multiple Modules

I am currently working with two separate modules that have completely different designs. To integrate these modules, I decided to create a new module called "accounts". However, when I include the line import { AppComponent as Account_AppComponent} from &a ...

Using jQuery to apply the wrapAll() function to each div element except the first child

I am looking to target all elements within a div with a specific class, excluding the first one. Here is the current HTML structure: <div class="cpt-cv-content-item"> <a>...</a> <h4>...</h4> ... </div> < ...

When zoomed in, the div background gives off a crisp white appearance

When I zoom in on a div with a background color or border, it appears completely white. Strangely, this issue doesn't happen when I zoom in on the Facebook site. This picture illustrates the problem more clearly. What could be causing this issue? H ...

Enhancing larger elements with a combination of CSS background-image gradients and border lines

My design calls for a background image with a line at the end. The line should start right where the background size ends, and in my concept it is grey. It's important that this line remains as one cohesive element. background-image: linear-gradient( ...

Web Audio API functions are encountering a playback issue on iOS 13.3, despite working smoothly on previous iOS versions

I have been developing an audio visualizer using the web audio API. It was functioning smoothly on PC, however, after upgrading to iOS 13.3, it no longer operates on Apple mobile devices. The root cause of this issue remains a mystery to me. The problem s ...

Ways to incorporate onload animation into a Pie chart with billboard js

I am currently working on implementing a pie chart with animation using billboard js. However, I am facing difficulties in applying the onload animation. Can anyone provide guidance on how to achieve this? For reference, you can view an example of the des ...

Managing image alignment in flexbox containers with nested rows and columns

In the following design demonstration, there are three blocks to explore. Block 1: Consists of three columns. The middle column contains two rows, both set to flex:1. Block 2: Also has three columns. The middle column includes two rows, but with a unique ...

What are some solutions for adjusting this sidebar for mobile devices?

My mobile version sidebar is not functioning properly on my website. To see the issue, you can visit Zinexium. As I am new to HTML, I don't know how to fix it. Here is a link to the code. Thank you! <!DOCTYPE html> // Code snip ...

JavaScript vs. markup: deciding between generating an extensive list of options or including them directly in

Recently, I encountered an issue with a .NET page that included a large number of identical dropdown lists within a repeater. Unfortunately, the rendering performance of the website was below expectations. In an attempt to improve the performance, I exper ...

What is the proper way to execute a JavaScript function within a JavaScript file from an HTML file?

I have the following content in an HTML file: <!DOCTYPE html> <!-- --> <html> <head> <script src="java_script.js"></script> <link rel="stylesheet" type="text/css" href="carousel.css"> & ...

Retrieve the file name of the webpage from the URL bar

Is there a way to retrieve the page name from the address bar using jquery or javascript instead of PHP? I am working on an HTML website and would prefer not to use PHP for this specific task. For example, if the address is www.mywebsite.com/hello.htm, ho ...

Drop the prohibited cursor before dragging

Is there a way to change the cursor behavior during element drag using HTML5 default drag and drop with TypeScript? I have tried various methods like changing from ev.target.style.cursor to "grab" cursor, adjusting dropEffect, etc., but none of them give m ...

utilizing a dynamic value within CSS modules for class naming

Struggling to incorporate a variable into a CSS module class name in Next.js. Finding it challenging to determine the correct syntax. The variable is fetched from the API: const type = red Here's how I'm attempting to achieve it: <div clas ...

Using jQuery to clear a textarea when a select input is changed

Currently, I am in the process of developing a small text editor that enables users to edit files and create new ones. Here is how I have set up my select menu. <select name="reportname" id="reportname" class="form-control"> <option value="zr ...

Take the user input from the form and incorporate it into the URL for the AJAX request

How can I dynamically update the URL in the AJAX call asynchronously? I've made a few attempts, but none of them seem to work. This is the current code: <!-- Input form --> <form class="navbar-form navbar-left" role="search" id="formversion" ...

Creating a duplicate or copy of an element in jQuery using

My dilemma involves a div that consists of text/images and a custom jQuery plugin designed for those images. The plugin simply executes a fadeIn/fadeOut effect every 3 seconds using setInterval. This particular div acts as a "cache" div. When a user wants ...

Ways to ensure that v-model does not become "true" or "false" in an input checkbox using Vue

I am currently working on a filter popup that includes a list of checkboxes. By default, some items should be selected and others not selected. I have connected these checkboxes to an object array using v-model. My issue is that when I deselect and select ...

Creating a Jquery slider animation: step-by-step guide

I tried implementing a code example in jQuery, but I am struggling with achieving smooth transitions in my slides. The changes are happening too abruptly for my taste. How can I create animations that occur during the transition, rather than after it? f ...

Significant performance disparity observed between Datatables in Internet Explorer compared to Chrome

I am facing a performance issue with a datatable that takes 4 seconds to render in Internet Explorer, while it loads quickly in Chrome. The ajax response from the server only takes less than 0.5 seconds to reach the client and it returns just 21 rows. I&ap ...