How to smoothly scroll a child div when the parent div is set as position sticky in vue JS

My landing page requires a unique feature: when a user enters a specific <section>, that section should become fixed while the elements inside the corresponding <div> start scrolling. Once the inner div has finished scrolling, the parent <section> should resume normal scrolling behavior and smoothly move to the top with a scroll.

I attempted to recreate this structure on jsFiddle but didn't achieve the desired functionality.

Check out my attempt on jsFiddle here.

I aim to replicate the behavior seen on this website. Specifically, Section SS as shown in the following image: https://i.sstatic.net/is4WR.png

Here's the HTML structure:


... Previous sections

    <section ref="stickyDiv" class="scroller py-sm-128">
      <div class="">
        <div ref="wrapper" @scroll="scrollerListener" class="wrapper-box">
          <div class="d-flex px-sm-128">
            <h3 class="section-heading">Access to all the exclusive opportunities</h3>
            <div class="col-sm-6">
              <img class="img-fluid"
                   src="https://res.cloudinary.com/stack-finance/image/upload/v1663728853/app-assets/v2/mask_group_590_e5gbgr.png"
              >
            </div>
          </div>
          <div class="d-flex px-sm-128">
            <h3 class="section-heading">Access to all the exclusive opportunities</h3>
            <div class="col-sm-6">
              <img class="img-fluid"
                   src="https://res.cloudinary.com/stack-finance/image/upload/v1663728853/app-assets/v2/mask_group_590_e5gbgr.png"
              >
            </div>
          </div>
          <div class="d-flex px-sm-128">
            <h3 class="section-heading">Access to all the exclusive opportunities</h3>
            <div class="col-sm-6">
              <img class="img-fluid"
                   src="https://res.cloudinary.com/stack-finance/image/upload/v1663728853/app-assets/v2/mask_group_590_e5gbgr.png"
              >
            </div>
          </div>
        </div>
      </div>
    </section>

... Further sections

Vue.js Method:

  methods: {
    ...
    listenBodyScroll(e) {
      if (this.isMobile) {
        return;
      }

      const stickyDiv = this.$refs.stickyDiv;
      const wrapper = this.$refs.wrapper;
      const dim = stickyDiv.getBoundingClientRect();
      console.log(dim.y, dim.height, '---scrollTop');

      if (dim.y <= 0) {
        if (Math.ceil(dim.height) <= Math.abs(dim.y)) {
          stickyDiv.style.position = 'relative';
          stickyDiv.style.top = 'auto';
          stickyDiv.style.height = 'auto';
          wrapper.style.overflowY = 'hidden';
          wrapper.scrollTop = wrapper.scrollHeight;
          return;
        }

        wrapper.focus();
        stickyDiv.style.position = 'sticky';
        stickyDiv.style.top = '100px';
        stickyDiv.style.height = '100vh';
        wrapper.style.overflowY = 'auto';
      }
    },
    scrollerListener({ target: { scrollTop, offsetHeight, scrollHeight, style } }) {
      if (this.isMobile) {
        return;
      }

      const stickyDiv = this.$refs.stickyDiv;

      if ((Math.ceil(scrollTop) + offsetHeight) >= scrollHeight) {
        stickyDiv.style.position = 'relative';
        stickyDiv.style.top = 'auto';
        stickyDiv.style.height = 'auto';
        style.overflowY = 'hidden';
        console.log('bottom!');
      }
    }
  }

VUE Directive for v-scroll:


Vue.directive('scroll', {
  inserted(el, binding) {
    const f = function(evt) {
      if (binding.value(evt, el)) {
        window.removeEventListener('scroll', f);
      }
    };
    window.addEventListener('scroll', f);
  }
});

Answer №1

Discover the inner workings of web development by utilizing your browser's inspect tool to delve into a website's HTML/CSS.

I personally tried this and extracted some HTML and CSS from a website to create a simpler version that you can view in this codesandbox

Essentially, there are two divs with 50% width positioned side by side within a shared parent div, ensuring they maintain the same (considerable) height. As you scroll the parent div into view, an image container with position: sticky keeps it fixed at the same screen position until reaching the bottom of its parent div, where it then scrolls along with the rest of the content.

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

Issue with Angular date field not displaying invalid input when form is submitted

I am encountering an issue with my simple form that contains only one date control. Whenever I input an invalid date like 30-Feb-2018, the control becomes invalid and my CSS style triggers a red border to indicate the error. The problem arises when the us ...

Submitting a form with Multer when the user chooses to upload a file or not

I have integrated multer into my express app for handling form submissions. The issue I am facing is with the optional image upload feature in the form. Users have the choice to add a photo if they want, but they should also be able to submit the form wi ...

Incorporating TypeScript into a project originally developed in JavaScript

I'm considering using TypeScript to write code for a JavaScript project. I've come to appreciate the benefits of TypeScript and am especially interested in using it for our AngularJS 1.5 project, which we plan to migrate soon. As I'm new to ...

transferring information from Facebook to a web address through ZAPIER

Looking for guidance on sending data from Zapier to FB lead fetch. Is there a direct way to do this or is an external PHP file necessary? I need to extract name and email and send it to my CRM that is not supported by Zapier, but can receive data through U ...

Are there any userscripts available for interactive websites?

I frequently create small GreaseMonkey UserScripts for my personal use. However, I often struggle with a recurring issue: How can I adapt to the changing nature of websites? For example, popular webstores like Amazon now update content dynamically withou ...

What is the best way to bundle a node module with the choice of adding submodules?

I am in the process of developing a JavaScript library that consists of a central core module and multiple optional submodules that enhance the functionalities of the core module. This library is specifically designed for the browser environment, utilizing ...

Tips on using the html() and toContain() functions in shallowMount in Vue to test a div that includes another component

I am encountering an issue with shallowMount in Vue. Here is my function: describe('ParentComponent.vue', () => { it('renders a ParentComponent', () => { const wrapper = shallowMount(ParentComponent, { propsData: { ...

Understanding intricate JSON structures with JavaScript

Here is the JSON structure that I am working with: var data = [ { "country":"Andorra", "code":"AD", "state":[ { "state_code":"AD1", "state_description":"aaAndorra1" }, { " ...

Enumerated data utilizing the v-for directive

How do I retrieve the data in likeNEW using v-for? You need to include [0] [1]. However, it is possible to achieve this without them. Likelike(){ axios .get('http://127.0.0.1:8000/api/v1/customer/like/', { headers: { Authorizat ...

I'm looking to create a JavaScript function that will extract each element from a div and then apply a corresponding CSS block to activate it

My goal was to create this function using Flask, but it seems that only JavaScript is capable of achieving it. This is my first attempt at coding it. Here's the code snippet: const navSlide2 = () => { const burger = document.querySelector(&apos ...

Efficiently update a multi-step form using Ajax and jQuery by adding new content without needing to reload the

Is it possible to create a multistep form on a single page without reloading the div with content from a PHP file, but instead appending it below? Here is my current progress: $(document).on('submit', '#reg-form', function(){ var ln = ...

How to send a contact form in Wordpress with multiple attachments via email without using any plugins

The main objective is to enable users to submit their own content for new articles (including text and files) to the administrator's email. A form has been created for this purpose: <form class="form form-send" enctype="multipart/fo ...

Send the object containing a Dictionary<string, int> parameter to the WebMethod

I encountered an error that says: "Cannot convert object of type 'System.String' to type 'System.Collections.Generic.Dictionary2[System.String,System.Int32]'","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertObje ...

Adding Custom CSS File to an iFrame in Angular

Currently, I am attempting to include a CSS file in a third-party iframe to modify its styling. My initial idea was to employ the following code snippet: ngOnInit() { ... this.myIframe.nativeElement.document.head.appendChild('style.css') } U ...

The ng-view DIV in Angular JS 1.x mysteriously vanishes

Currently, I am working on a project that involves angularJS and ASP.NET in Visual Studio 2013. However, I have encountered a frustrating issue where my DIV node for ng-view is being replaced with an ng-view comment without any errors appearing while testi ...

Struggling with implementing responsive mobile buttons that stack in a column? Here's the solution

My content is nearly responsive on all screen sizes, but I'm having trouble getting the buttons to stack neatly in a column. Can anyone provide suggestions on how to fix this issue? You can view the current progress below. Thank you in advance for any ...

The Axios request for the concatenated URL is failing to execute

Encountering an issue with Axios in node js. Here's the code snippet: let callResult = await axios.get(urlData, config) The configuration object used is as follows: let config = { headers: { 'X-Token': token } ...

Running a child process within a React application

I'm currently in search of the best module to use for running a child process from within a React application. Here's what I need: I want a button that, when clicked, will execute "npm test" for my application and generate a report that can be r ...

What is the best way to maintain the CSS3 animation state following ng-animate?

Attempting to alter the state of a div using ng-animate along with CSS3 transitions. The animations are functioning well with this particular CSS, except for the issue where the div loses its size and color once the animation is completed. .fade-hide, .f ...

What are some clever ways to handle the transition of the display property?

While transitions for the display property may not work, I am exploring alternatives. I attempted using the visibility property but it didn't quite fit my needs. In my current setup, different text is displayed when hovering over an anchor tag by sett ...