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.

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

Generating Dynamic Widgets Within the Document Object Model

Currently, I am working with jQuery Mobile 1 alpha 1. In order to create a text input field using jQuery Mobile, you need to include the following HTML code: <div data-role='fieldcontain'> <label for='name'>Text Input:</ ...

Submitting a form through AJAX, even when using the $(this) function for another form

Currently, I have a situation where there are two forms present on my page. The first form is located in the footer and serves as a contact page. The second form, named "product-form," is considered to be the main form. Within this form, PHP validation is ...

Go back to the previous operation

Utilizing ajax to verify if a username is available by checking the MySQL database. If the username is already taken, it will return false to the form submit function. index.php $("#register-form").submit(function(){ var un = $("#un").val(); $.aj ...

Updates in dropdown events when options data has been modified

Hey there, I'm wondering about dropdown events. Let's say I have two dropdowns. When a selection is made in the first dropdown, all options in the second dropdown are replaced with new ones. For example, let's say the first dropdown has thes ...

When clicking on the text areas, the Twitter-Bootstrap drop-down login automatically closes

Greetings! I am currently working on my first website design using JQuery. My project includes a dropdown login box created with Twitter-Bootstrap. Unfortunately, I'm facing some challenges with the JQuery script that controls the behavior of the logi ...

I am having trouble placing the button within the image

Essentially, my goal is to place the button within the image and ensure it remains in its position when transitioning to mobile mode or adjusting window size. This is the desired outcome: https://example.com/image https://example.com/button-image .img ...

Sending the results from a Vue.js component to a text input field in HTML

Using vue.js and the v-for function to read QR codes has been a challenge for me. For example: <ul v-for="(scan,key) in scans" :key="key" > {{scan.content}} </ul> I need to extract the value inside {{scan.content}}, like an EmployeeID, but I ...

Sending Rails form data to a JavaScript click event

I'm currently working on a user profile form with a "Submit" button that triggers some client-side validations before proceeding. In my code, I've set up an intercepting click event on the submit button to run the validations and then proceed wi ...

Is it possible to modify the value on the src img tag prior to scraping the data

Hey everyone, check out this piece of code I have: foreach ($image as $snimka){ $url = $snimka->src; $ch = curl_init($snimka->src); $fp = fopen('images/' . basename($url), 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp ...

Tips for creating a clickable ::before image

I'm trying to create a hover effect where an image appears and is clickable when hovering over an element, similar to what is seen on many websites. For example, I want to display a bin icon when hovering over an element by using the ::before pseudo-e ...

To display the user's input value in the console log upon clicking

Having trouble displaying the user's input value in the console when the button is clicked. function submit(){ var userInput = document.getElementById('input_text').value; console.log(userInput); } ...

Tips for creating visually appealing text on a web browser with the help of open-source libraries

Have you ever noticed that no matter how we display text on webpages, whether it's in a <p> tag or an <h1> tag, the result is always the same? (a screenshot of a rendering done in Firefox) Do you struggle with pixelated areas on the curv ...

Every single image within a specific domain

Exploring a way to create a gallery showcasing all the images within my domain's internet root folder. These images are scattered across various folders. What is the most efficient method to navigate through these folders and display the images? ...

ms-card malfunctioning due to data issues

I'm facing difficulties in transferring the data to the template. Although I can access the data in HTML using vm.maquinas and maquina, I am unable to pass it to the TEMPLATE through ng-model. Information about ms-cards was not abundant. Module ang ...

The error message "Cannot read property 'option0' of undefined" occurs when using Node.js with Express and EJS

script.js var choices = { choice0: 11, choice1: 'choice1', choice2: 'choice2', choice3: 'choice3', choice4: 'choice4', choice5: 'choice5', choice6: 'choice6', choice7: 'choice7', choice ...

Discovering the exact distance between a 'li' and a 'div' element

Currently, I am in the process of converting HTML to JSON. Here is an example of the HTML I am working with: <div class="treeprofit" id="divTreeViewIncomeDetails" style="height: auto;"> <li><span class="fa fa-folder-open highlight" ...

Adjust the header's alignment to seamlessly coincide with the uppermost part of the

I'm encountering this peculiar issue with a website I recently started designing. My aim is to make the header perfectly aligned with the top of the page. However, despite my attempts, there persists a stubborn gap that measures around 20px, defying a ...

retrieve the Jquery progress bar's current value

Having trouble determining the value of the progress bar in order to increase it by a percentage with each step. No matter what I attempt, I keep getting errors such as 'undefined' or 'method cannot be called before object instantiation.&apo ...

The Jquery ajax page is redirecting automatically when a post request is made

Encountering an issue while attempting to upload multiple files through AJAX, as the process redirects to a blank page displaying only the names of the uploaded files. Here is the HTML tag: Below is the JavaScript function: function upload(){ var proje ...

Is there a way to repurpose a JavaScript object that gets sent back to the client upon page loading?

Upon initial page load, an AJAX request fetches a list of JavaScript objects which display only one value each. The page includes buttons to expand each item and reveal the remaining values. Originally, I used another AJAX call to retrieve individual objec ...