Navigating through each segment

I'm currently working on a website with sections that are set to be 100% height of the window, but at least 800px tall.

My goal is to implement a smooth scrolling functionality where one scroll moves the view from section to section. However, if the scroll distance is less than 800px, it should act as normal scrolling until reaching the end or start of a new section.

I attempted to write a script myself, but it's not performing as well as I'd like.
Is there a reliable script or tutorial available for this purpose?

(Here is my current attempt, which hasn't been successful...)

var prevScroll = $(window).scrollTop();
var currentSection = getCurrentSection();

$(window).scroll(function(){
    var newScroll = $(this).scrollTop();
    if (newScroll > prevScroll){
        checkScrolling("down");
    } else {
        checkScrolling("up");
    }
    prevScroll = newScroll;
});


function checkScrolling(direction) {

    var fromTop = $(window).scrollTop();
    var windowHeight = Math.max($(window).height(), 800);
    var currentPlace = $(currentSection).offset().top;

    if ( direction == "down" ) {
        if ( currentSection != ".blogs" ) {
            var nextPlace = $(currentSection).next().offset().top;
            if ( fromTop+windowHeight >= nextPlace ) {
                $("html, body").animate({scrollTop: nextPlace}, 1000);
                setTimeout(function(){
                    currentSection = getCurrentSection();
                }, 1001);
            }
        }
    } else {
        if ( currentSection != ".about" ) {
            var prevPlace = $(currentSection).prev().offset().top;
            if ( fromTop <= prevPlace+windowHeight ) {
                $("html, body").animate({scrollTop: prevPlace}, 1000);
                setTimeout(function(){
                    currentSection = getCurrentSection();
                }, 1001);
            }
        }
    }
}

function getCurrentSection() {
    var fromTop = $(window).scrollTop();
    var windowHeight = Math.max($(window).height(), 800);
    var s1 = $(".about").offset().top;
    var s2 = $(".works").offset().top;
    var s3 = $(".blogs").offset().top;

    if ( s1 <= fromTop && fromTop < s1+windowHeight ) {
        return ".about";
    } else if ( s2 <= fromTop && fromTop < s2+windowHeight ) {
        return ".works";
    } else if ( s3 <= fromTop && fromTop <= s3+windowHeight ) {
        return ".blogs";
    }
}

Answer №1

I highly recommend checking out ScrollMagic for creating stunning scroll animations.

Answer №2

I came up with a small jQuery script to handle responses. To test it, copy and paste the answer code and try using the up and down arrow keys.

var prevScroll = $(window).scrollTop();
var currentSection = getCurrentSection();


$(document).keydown(function(e) {
    var newScroll = $(window).scrollTop();
    switch(e.which) {
        case 38: // up
         checkScrolling("up");
        break;

        case 40: // down
         checkScrolling("down");
        break;

        default: return; // exit this handler for other keys
    }
    prevScroll = newScroll;
    e.preventDefault(); // prevent the default action (scroll / move caret)
});
;


function checkScrolling(direction) {

    var fromTop = $(window).scrollTop();
    var currentSection = getCurrentSection();
    var windowHeight = Math.max($(window).height(), 800);
    var currentPlace = $(currentSection).offset().top;

    if ( direction == "down" ) {

         if( $(currentSection).next().length > 0){
                var nextPlace = $(currentSection).next().offset().top;
                $("html, body").animate({scrollTop: nextPlace}, 1000);
                $(currentSection).removeClass("current").
                next().addClass('current');
        }

    } else {
        if( $(currentSection).prev().length > 0){
                var prevPlace = $(currentSection).prev().offset().top;
                $("html, body").animate({scrollTop: prevPlace}, 1000);
                $(currentSection).removeClass("current").
                prev().addClass('current');
        }
    }
}

function getCurrentSection() {
    return  $(".current");
}
body{
margin:0;
padding:0;
width: 100%;
height: 100%;
position: absolute;
}

body section{
width: 100%;
height: 100%;
box-sizing: border-box;
max-height: 800px;
}

body section:nth-child(1){
background: grey;
}
body section:nth-child(2){
background: red;
}
body section:nth-child(3){
background: yellow;
}
body section:nth-child(4){
background: cyan;
}

body section[class=current]{
border: 2px solid #000;
}
<!DOCTYPE html>
<html>
<head>
<title>Test Scroll</title>
<link rel="stylesheet" type="text/css" href="css.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js.js"></script>
</head>
<body>
<section class="current">
</section>
<section>
</section>
<section>
</section>
<section>
</section>
</body>
</html>

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

Toggle visibility of table columns by selected options (using jQuery)

I am seeking to create a dynamic table that only shows specific columns based on the selection in a dropdown menu. <table> <thead> <td colspan="5"> <SELECT name="menu"> <option value="eur">EUR</option> & ...

The continuous firing of the postback event of the Asp.Net Button is

Why does the postback event keep firing for my button? Strangely, when I try to debug with Firebug and set a break point on the function(e) part, the code seems to skip right over it. Even using return false doesn't seem to resolve the issue. <sc ...

Keep fancybox items in their designated spot

When the window is opened at full size, everything looks fine. However, when you resize the window horizontally, the thumbnails shift and disappear. I want them to remain fixed in their position like the large pop-up image so that users can still see them ...

Having trouble with request-promise in node.js? It's not functioning as anticipated

Currently utilizing the request-promise node module. Following the documentation closely to ensure correct setup, however encountering the following error: Unhandled rejection StatusCodeError: 400 - "{\n \"error\" : {\n \"s ...

Exploring the functionality of the readline module using a simulated command-line

I am currently working on developing a unit test for a module that utilizes the "readline" functionality to interpret standard input and provide standard output. Module: #!/usr/bin/env node const args = process.argv.slice(2) var readline = require(' ...

Unlocking the Secrets: Javascript Tricks for Retrieving Object Values

I have an item that contains data which I need to display. {"text": "active user active user213123 idle user234234234 loggedout userafdadf" }, To extract the content, I used the following code: Response = message.s ...

Encode data in JSON format using Javascript and then decode it using PHP

In my coding journey, I decided to create an object using Javascript to pass it as an argument to a PHP script. var pattern = new Object(); pattern['@id'] = ''; pattern['@num'] = ''; pattern.cprop = new Object(); // ...

Stop the scrolling behavior from passing from one element to the window

I am facing an issue with a modal box window that contains an iframe. Inside the iframe, there is a scrollable div element. Whenever I try to scroll the inner div of the iframe and it reaches either the top or bottom limit, the browser window itself start ...

Creating an HTML form to collect user data and then automatically saving it to an Excel file stored in a shared Dropbox account

I am looking to extract data from a user form on a website and then automatically save it as an Excel file in a designated Dropbox account once the user clicks submit. Instead of receiving multiple emails every time the form is filled out, I would like t ...

What is the process for using AJAX and PHP to upload an image file?

I'm facing an issue where I want to insert an uploaded image into a database with user details for a profile picture. The output I receive currently shows {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}. How can th ...

Issue encountered with CSS3 animations, failing to perform as intended for various animations

In my project, I have a series of div elements that I am animating in various ways. The first one utilizes a cardflip animation effect: @-webkit-keyframes cardflip { from { -webkit-transform: perspective(2000) rotateY(90deg); -webkit-tra ...

In AngularJs, users can select multiple options using check-boxes, which will automatically generate a tag based on the selected choices. Additionally,

I am looking to implement a feature where users can make multiple selections using checkboxes. Based on their selections, tags will be created using an Angular directive. If a user selects multiple checkboxes, corresponding tags should be generated. If a t ...

Significant Google Maps malfunction detected with API V3

Update: Issue resolved, check out my answer below. The scenario: User interacts with a map-image google maps API V3 is loaded using ajax the map is displayed in a dialog window or lightbox What's going on: The map loads and all features are funct ...

Ensure that the text inside the button does not exceed its boundaries (utilizing Bootstrap v4)

My current code snippet appears below. <div class="col-xl-2 col-lg-12"> <button class="btn btn-secondary w-100" value=1>But.</button> </div> <div class="col-xl-4 col-lg-12"> <button cla ...

Update the icon class for the Kendo Date Picker using jQuery

Looking to implement the kendo Jquery Date Picker feature but encountering some issues. I've been consulting https://docs.telerik.com/kendo-ui/controls/editors/datepicker/overview.html for guidance. Instead of the default k-i-calendar class, I' ...

Using shadow effects on the <Grid> component with Material UI

Is there a way to implement the box-shadow property on a <Grid> component in Material UI? I've gone through the official documentation regarding Shadows - Material UI, but I'm struggling to grasp how it can be applied to a <Grid>. De ...

What steps should I take to incorporate Google AdSense advertisements onto my website?

After developing a website using HTML and PHP, I attempted to incorporate Adsense ads. However, upon inserting the ad code between the body tags, the ads failed to display on the site. How can I resolve this issue? ...

Determining the duration since generating a unique objectid in mongodb

I am currently developing an application that offers users the option to reset their passwords. The process is quite straightforward - after entering his email address, the user will receive a link containing the new objectid number. For example: /reset- ...

Floating action buttons in CSS

I'm trying to create a button that reveals additional options when hovered over. I've been looking for a method similar to what's shown in the image below, but haven't been successful. This needs to be implemented on a web page using HT ...

The issue of sluggishness in Material-UI when expanding the menu is causing delays

Watch Video Having trouble with the behavior of the Menu opening and closing similar to this example. The text seems slow to change position. Any ideas why? This is the devDependencies configuration I am using in webpack. "devDependencies": { ...