Tips for preventing a child div from moving when scrolling towards it and creating an internal scroll with a smooth animation using either JavaScript or jQuery

Looking to add scrolling functionality with animation to a child div on my webpage? Check out this example.

I attempted using JavaScript's on scroll function, but it didn't work as expected. Currently, I have it set up to trigger on click of certain cards, but ideally, I would like it to activate when the div is scrolled.

This example module represents just one part of my website; there is content both before and after it. Essentially, this module sits in the center of the site.

Here is some sample code I tried:

function scrollFunc() {
  alert("is this working properly?");
  document.getElementById("platform-cards").style.backgroundColor = "black";
  document.getElementById("cards-main-div").style.display = "none";
  document.getElementById("card-info-div").style.display = "block";
}

html code

<div class="cards" onscroll="scrollFunc()">
</div>

and another attempt:

const cardMainDiv = document.querySelector('.cards-main-div');
cardMainDiv.addEventListener('scroll',(e)=> {
alert("it is working....")
// EVEN ALERT IS NOT WORKING
  document.getElementById("platform-cards").style.backgroundColor = "black"
  document.getElementById("cards-main-div").style.display = "none"
  document.getElementById("card-info-div").style.display = "block"
});

html code

<div class="cards">
</div>
<div class="card-info-div" id="card-info-div">
</div>

Answer №1

Take a look at this sample code to see how you can achieve your desired outcome. I hope you find it useful.

const scrollDiv = document.querySelector('.scrollDiv');
    scrollDiv.addEventListener('scroll', (e)=>{
      // Do whatever on scroll
      // I am just changing the background color of div
      const target = e.currentTarget;
      target.style.backgroundColor = 'red';
    });
 body {
      min-height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    h1,
    p {
      margin: 2rem 1rem;
    }

    .scrollDiv {
      width: 200px;
      height: 200px;
      overflow: scroll;
    }
<div class="maindiv">
    <h1>Title</h1>
    <div class="scrollDiv">
      Lorem ipsum dolor sit amet consectetur, adipisicing elit. Recusandae, autem ut doloribus inventore odit temporibus
      eaque voluptas laboriosam, tempora quia optio a enim accusamus nostrum repellat maxime accusantium asperiores. Ex
      voluptatem sequi aut autem laborum temporibus. Sit obcaecati inventore illum molestias quo vero at, necessitatibus
      dolores a doloremque accusamus eum.
    </div>
    <p>What are you doing?</p>
  </div>

This event will only trigger when scrolling within the internal div.

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

I need to link the click function to the li components within the xpages autocomplete feature

I've successfully implemented Tim Tripcony's advanced type-ahead solution and it's working well. However, I'd like to customize it a bit by redirecting the user to the selected document instead of filling the editbox with the selected d ...

How to properly display date format in Node.js when using EJS templates with MySQL

When retrieving dates from the database, I am looking to break them down into two separate numbers. 7:00-8:00 //array[0]=7:00 and array[1]=8:00 9:00-9:30 14:30-15:00 Below is my code, but it is returning NaN NaN: <% time_slots.forEach((timeslot ...

Is it possible to showcase the data from three or more PHP files on a single webpage?

I currently have three PHP files: pie.php, bar.php, and line.php. When each file is run individually, it displays a webpage with a pie chart, bar chart, or line graph respectively. However, running all three files opens up separate webpages for each graph. ...

JavaScript checkboxes not being recognized by Node element

Located on the left side of the page, there is a feature that allows me to include selected options in a list with the same name attribute. These selections will then be sent as part of the entire form to the Node backend. Most of the elements on the page ...

Having trouble with your contact form sending messages?

Looking for some assistance with the Contact form on this Codepen page: https://codepen.io/ssbalakumar/pen/uzDIA The form is displaying correctly on my website, but when I try to submit it, the page reloads and I'm unsure where the message is being ...

Share your Facebook link with dynamic parameters

When attempting to create a share URL with GET parameters, I am encountering some issues with double encoding. <a href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.bing.com%2Fsearch%3Fq%3Dkeyword" /> This results in a faulty URL, while &l ...

When the user signs in with Next-auth, they will be redirected to /signin with

After following the documentation to implement next-auth, I encountered an issue. When I visit http://localhost:3001/api/auth/signin, I see a page with a link (https://i.stack.imgur.com/xb0fx.png) but clicking "signin with Google or GitHub" just refreshes ...

Struggling to Personalize Kendo Calendar Month templates using Knockout Kendo JS Binding

I have made modifications to the Kendo Calendar Month Template Resource which can be found Here without utilizing knockout-kendo.js. The official Kendo Reference is available Here. The issue arises when I implement the following code in knockout-kendo.js ...

Having trouble processing a JSON object using Jquery?

Hello, I am currently working on parsing a JSON object using jQuery. So far, I have successfully extracted all the necessary information from the results except for one crucial piece - the performance tags. Each JSON result is enclosed in an event tag and ...

Sending parameters to async.parallel in Node.js

My goal is to create a simple example that demonstrates the concept I have described. Below is my attempt at a minimal example, where I expect to see the following output: negative of 1 is -1 plus one of 2 is 3 Here is the code I've written: var asy ...

Unexpected Ajax status code of 0 encountered during page refresh

My application retrieves page data using a $.ajax call on page load. If the user reloads the page or navigates to another page before the response arrives, an error is triggered with status code 0. Some people suggest ignoring these errors by adding this p ...

Organize the JSON data in a particular manner

I have a set of JSON data that looks like this: [ { "name": "Event 1", "sponsors": [ { "name": "Walmart", "location": "Seattle" }, { "name": "Target", "location": "Portland" }, { ...

Could we add a touch more to the favicon?

After searching far and wide on this site and Google, I have come up empty-handed in my quest to resolve my favicon dilemmas. Despite delving into various tutorials, the concept of favicons still eludes me. The idea that clearing the cache could be a sol ...

Utilizing Conditional Statements in the @artsy/fresnel Framework

I recently started working on a responsive React application using the @artsy/fresnel npm package. Below is a snippet of the code I have implemented: <Media greaterThanOrEqual='computer'> <div style={{ padding: '20px 50px' ...

Using Angular service worker to pre-fetch video files

Issue arises when the service worker prefetches the entire video embedded on the page, leading to performance problems. My ngsw-config.json only contains configurations for local files, whereas the video is located on a different subdomain under /sites/def ...

Tips for retrieving input values when they are not available in HTML documents

In this code snippet, I am creating an input element with the file type without adding it to the DOM. My goal is to retrieve the value of this input once the user selects a file. Even though the input is not part of the HTML template, I still want to acces ...

Convert an array comprising arrays/objects into JSON format

This problem is really challenging for me. The structure of my array goes like this: array1 = [ [array2], [array3], [array4] ... [array17] ] array2 = [ ['obj1'], ['obj2'], ['obj3'] ... ['obj30'] ] ... ... obj1 = ({p ...

CSS DROP DOWN NAVIGATION MENU - Struggling to maintain hover effect on main menu item while navigating through sub-menu

I am facing a challenge with a CSS-only drop-down menu where the top main menu item loses its highlight when I move the cursor over the sub-menu items. You can view the menu in action here: . For example, if you hover over "Kids" and then move your cursor ...

Centered buttons placed right next to each other

Having trouble getting my buttons centered and aligned side by side on the screen. I've managed to achieve one or the other but not both simultaneously. Currently, the buttons are next to each other but positioned at the top left corner of the screen. ...

I am currently using React to implement a feature that displays random facts for 5-second intervals. Despite no errors being displayed, the facts are not appearing on the page as expected

Client side My react application includes a section that is supposed to display random facts at 5-second intervals. Although no errors are displayed, the facts do not appear on the page when I run the code. import React from "react"; import &quo ...