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

Send a response from socket.io to the client's browser

I am working on a project where I need to retrieve the ID of the current drawer from the server and pass it to the client. Here is the code I have so far: Client Side: socket.emit('returnDrawer'); socket.on('returnDrawer', fu ...

Avoid cascading of the 'display' property in JavaScript styling to prevent inheritance

Is there a way in Javascript to toggle the visibility of a larger portion of HTML without affecting inner display properties with display: <value>? Despite setting an outer display property using Javascript, the inner display properties are also alt ...

Monitor fetch() API calls and responses in JavaScript

I’m looking to intercept fetch API requests and responses using JavaScript. Specifically, I want to be able to capture the request URL before it is sent and also intercept the response once it has been received. The code below demonstrates how to inter ...

How can I convert Typescript absolute paths to relative paths in Node.js?

Currently, I am converting TypeScript to ES5/CommonJS format. To specify a fixed root for import statements, I am utilizing TypeScript's tsconfig.json paths property. For instance, my path configuration might look like this: @example: './src/&ap ...

What is the method of utilizing shared services when the controllers do not rely on any shared services?

Let's imagine a scenario where there is a module containing only one factory, which serves as the shared service. angular.module('sharedService', []) .factory('sharedSrv', sharedService) function sharedService() { var numbe ...

Rewriting URLs in Angular 2

I am a beginner in Angular 2 and I am currently working on a project that requires URL rewriting similar to that of ' '. In Zomato, when you select a city, the city name appears in the URL like ' ', and when you select a restaurant, t ...

Tag utilizing jQuery

Check out my JSFiddle. I'm looking to change the h2 name to a hashtag and update it when the next button is clicked. Does anyone have a solution for this? ...

Is there a way to extract a token from the URL in a Nextjs/React application?

I am currently developing a project that relies heavily on API integration. My front-end interface is built using React and Next.js, while the back-end API is developed with Laravel. Within my front-end page, I have implemented a token in the URL to help ...

Looking for an uncomplicated SSO system similar to Google Identity Toolkit but with a customizable UI interface?

I'm really impressed with the Google Identity Toolkit, it's so user-friendly and easy to set up! However, I'm having trouble with the fact that it forces me to use its UI. Is there another option available that will allow visitors to simply ...

The header, main content, and footer sections expand to occupy the entire page

I am in need of HTML structure that looks like the following: <header></header> <div id='main'></div> <footer></footer> I want all elements to be positioned relatively. The header and footer will have fixed h ...

Using ASCII 3D text can create a stunning visual effect on a website, but it can sometimes appear

My website is displaying ASCII 3D Text with glitchy lines, but this issue is not present on other websites. Example 1: Glitchy lines visible on my website Example 2: A different website using the same text without any glitchy lines. No glitches detected h ...

Why is the view not reflecting the updates made to the model?

I recently started delving into Angular JS and have been following tutorials to learn it. One issue I'm facing is that my model doesn't seem to update the view. Can anyone help me figure out why this is happening? Here is the code snippet: < ...

Error: The 'filename' property of undefined cannot be read when attempting to upload a user profile photo using multer

I am facing an issue while attempting to upload a user profile photo using express.js server and Multer. I keep receiving the error message "TypeError: Cannot read property 'filename' of undefined." Below is the code snippets for both the server- ...

I am interested in creating a class that will produce functions as its instances

Looking to create a TypeScript class with instances that act as functions? More specifically, each function in the class should return an HTMLelement. Here's an example of what I'm aiming for: function generateDiv() { const div = document.crea ...

Decoding JSON with HTML in c#

While serializing an object into JSON that contains HTML, I encountered a unique issue. Below is the structure of my class: [Serializable] public class ProductImportModel { public string ProductName { get; set; } public string ShortDescription { get; ...

Creating a table with both a fixed header and a fixed column using only CSS

I'm looking to create an HTML table with a fixed header and fixed first column, but I want to avoid using JavaScript or jQuery to set scrollTop/scrollLeft for smooth functionality on mobile browsers. I found a solution that fixes the first column he ...

Integrating tooltips on Dimple.js line charts

A simplified network-style chart has been created using Dimple's line plot as the foundation. For example, please refer to this link: http://jsfiddle.net/cc1gpt2o/ myChart.addCategoryAxis("x", "Entity"); myChart.addCategoryAxis("y", "Entity").add ...

Why isn't the function in my React child component passing its parameters to the parent component's function as expected?

In the parent: const [currentPinPosition, setCurrentPinPosition] = React.useState({ lat: 0 , lng: 0 }); const updateCurrentPinPos = (position) => { console.log(position); setCurrentPinPosition({ lat: position.lat, lng: position.lng }); }; / ...

Steps for creating a basic table filter using jQuery

What is an efficient way to create a basic table filter using jQuery without pagination requirements? I want to retrieve data from a database and display it as a list. I would like to avoid using plugins and instead opt for concise code snippets. For ...

Struggling with navigating JSON data in JavaScript and facing difficulties sorting the array

I am currently facing the challenge of organizing data obtained from an API using JavaScript. JavaScript Code to Retrieve Data: function getResults() { var url = $.getJSON("http://api.api.com&leagues=SOCENGPRE&lang=en&format=jsonp&cal ...