The concept of "HTML paragraph shifting"

I am looking to implement a feature similar to paragraph sliding, but I am struggling to explain it clearly.

For demonstration purposes, I have added it to my website for you to view. Please note that it may take some time to load.

The paragraphs slide sequentially like this one after another.

I attempted to write the code myself, but did not receive any response after implementing it.

Below is the code I have written:

var mousewheel = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel";

var IDK = 1;
slide.addEventListener(mousewheel,
        function (e) {
            if (e.wheelDelta > 0 || e.detail < 0) {
              IDK + 1 
              $("html,body").animate({scrollTop: $("#" + IDK ).offset().top}, 1000);
            } else {
                if(IDK=1){
                  console.log("NO")
                }else{
                  IDK - 1
                  $("html,body").animate({scrollTop: $("#" + IDK ).offset().top}, 1000);
                }
            }
        }, false);

If you can provide guidance on how to improve my code, I would greatly appreciate it.

Please excuse any errors in my English, as it is not my first language.

Answer №1

Did you intend for this to be the solution?

//Adjust the height of each section to match the window height
    $('section').height($(window).height());
    /*Add the class 'active' to the first element 
     as an indicator*/
    $('section').first().addClass('active');

    /* Handle mousewheel event and DOMMouseScroll together to ensure cross-browser compatibility */
    $(document).on('mousewheel DOMMouseScroll', function (e) {
        e.preventDefault();//prevent default mousewheel scrolling
        var active = $('section.active');
        //Determine if scroll is UP or DOWN
        var delta = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? 1 : -1;
        
        //If delta is negative, user is scrolling down
        if (delta < 0) {
            //Scroll down handler
            next = active.next();
            //Check if next section exists and animate the scroll
            if (next.length) {
               /*Using setTimeout to prevent abrupt jumping during fast scrolling*/
                var timer = setTimeout(function () {
                    /* Animate scrollTop to next element's offset top value */
                    $('body, html').animate({
                        scrollTop: next.offset().top
                    }, 'slow');
                    
                    // Move the 'active' class indicator
                    next.addClass('active')
                        .siblings().removeClass('active');
                    
                    clearTimeout(timer);
                }, 800);
            }

        } else {
            //Scroll up handler
            /*Similar logic to scroll down handler but anchoring to previous sibling */
            prev = active.prev();

            if (prev.length) {
                var timer = setTimeout(function () {
                    $('body, html').animate({
                        scrollTop: prev.offset().top
                    }, 'slow');

                    prev.addClass('active')
                        .siblings().removeClass('active');
                    
                    clearTimeout(timer);
                }, 800);
            }

        }
    });
body, html {
    margin:0;
    padding:0;
    overflow:hidden;
}
section {
    height:100vh!important;
    font-size:30px;
    display:flex;
    justify-content:center;
    align-items:center;
    color:white;
}
.bg1{background-color:#FAAD80;}
.bg2{background-color:#FF6767;}
.bg3{background-color:#FF3D68;}
.bg4{background-color:#A73489;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="bg1">First</section>
<section class="bg2">Second</section>
<section class="bg3">Third</section>
<section class="bg4">Fourth</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

Tips for preventing redundant function calls to a prop within a ReactJS component

I am currently facing an issue where I am repeatedly calling the same function within a component to retrieve a specific prop inside the render function. Is there a way to optimize this and avoid calling the function multiple times for each required prop ...

The requested 'Pagination' component (imported as 'Pagination') could not be located within the 'swiper' library. Possible exports include Swiper and default

I was trying to implement pagination using swiper. I included the Pagination module with this import statement: import { Pagination } from "swiper"; Here's my configuration: https://i.sstatic.net/1iqoi.png The error that I encounter ...

Images Are Failing to Load on the Webpage

I'm facing an issue with appending pictures of restaurants to dynamic div IDs. When I make the div ID static, the pictures show up fine from the server, but when I try to make it dynamic, the images don't get appended. Can someone please assist m ...

Managing a database update when server actions involve various form types

My UI dashboard contains multiple forms like "edit title" and "edit description", each with just one input element. I am looking to streamline database updates and server actions in next js 14, utilizing useFormState on the front end. While I have achieve ...

JavaScript getting overshadowed by other JavaScript libraries

My current CMS, Liferay, heavily relies on jQuery for various functions. Recently, I introduced a new feature to our website using fancybox. However, I realized that this new addition was causing issues with other jQuery functionalities on the page. Remov ...

Ajax experiences trouble with a intricate sequence of characters

How can I successfully send the following string to a spring MVC controller using ajax: (?=^.{8,}$)(?=.+\d)(?=.+[!@#$%^&]+)(?!.*[\n])(?=.+[A-Z])(?=.+[a-z])$ I am encountering a 400 bad request error and it is not leaving the client side. An ...

When attempting to call a bundle file using browserify from React, an unexpected character '�' Syntax error is thrown: react_app_testing/src/HashBundle.js: Unexpected character '�' (1:0

Hey there, I'm currently struggling with an unexpected unicode character issue. Let me provide some context: I've created a simple class called HashFunction.js that hashes a string: var crypto = require('crypto') module.exports=class H ...

Add a JSON file containing an image path as a value into a CSS background property

I currently have a MongoDB database containing documents with 'img' values structured as follows: "img": "../folder/img.jpg" Would it be feasible to utilize this string in my CSS for modifying the background image? This is essential because I n ...

Utilizing a Function's Return Value as a State in React - A Comprehensive Guide

Currently, I am delving into the realm of functional components within React and have crafted a simple piece of code that should output 'Nah' if the state value is at 0. However, there seems to be an issue as this functionality does not seem to ...

"Adjusting the AJAX call destination based on the current view or page: A step-by-step guide

I am currently conducting tests on a .js script using Qunit. Within my static .html test harness, I have included the .js "code under test" (CUT) along with appropriate markup. The actual testing is happening in another script that is also incorporated in ...

Having trouble scrolling to the top in Flickr Search using AngularJS, the results are restricting my movement

I recently followed a tutorial on creating a Flickr Search App with AngularJS (https://www.youtube.com/watch?v=lvGAgul5QT4). I managed to show the search results on my page, but encountered an issue: I couldn't scroll all the way back up to the search ...

attempting to refine an array of objects using another array within it

I am currently filtering a group of objects in the following manner: [ { "Username":"00d9a7f4-0f0b-448b-91fc-fa5aef314d06", "Attributes":[ { "Name":"custom:organization", "Valu ...

Ways to allocate space evenly between components of the same size in React Native

As a beginner in Javascript and React-native, I have been experimenting with the technology to assess its viability for potential use in my current workplace. However, I have encountered some challenges with the user interface. To enhance my understanding ...

Regularly check in with the server via ajax calls

I have a page that needs to send periodic "background" ajax requests after it is loaded. These requests should be sent at specific time intervals. Would using cron be the best option for this task, considering that I have never used it before? Are there a ...

Guide on sending a sizable item as a string utilizing Axios

In order to efficiently save a large and complex object as a JSON file on the server without needing to map it to an object in C# first, I am facing some challenges. Sometimes, when posting the object as a string, the data gets corrupted leading to errors ...

What is the process for the Rebol programming language to independently implement an asynchronous pluggable protocol for reading

This post outlines the process of incorporating an asynchronous pluggable protocol in Rebol that can be accessed through Firefox, Internet Explorer, or the command line For instance, if I were to define the reb:// protocol, I could enter it into a browser ...

Parsing error: 'Unexpected token' found in JSON while attempting to access an external file

Currently working on implementing backbone for a new project along with underscore, requirejs, jquery, and bootstrap. Things are progressing smoothly as I aim to include static survey question data into one of the data models. { "defaultOptions": { ...

Extract branch, path, and URL from the .gitmodules file by utilizing JavaScript Regex

Is there a way to extract branch, path, and URL details from the .gitmodules file using JavaScript Regex? .gitmodules [submodule "PATH"] path = <PATH> url = <URL> [submodule "PATH"] path = <PATH> url = <URL> ...

utilizing vueJS for global notifications

It may sound like a cliché question, but I still haven't grasped it. I have a primary component that is always loaded in the application. Let's refer to it as DefaultContainer.vue <template> <div class="app"> .... Notifi ...

Could the autofill feature in Chrome be turned off specifically for Angular form fields?

Even after attempting to prevent autofill with autocomplete=false and autocomplete=off, the Chrome autofill data persists. Is there a method to disable autofill in Angular forms specifically? Would greatly appreciate any recommendations. Thank you. ...