Automatically scroll to each div or element on the page

Can anyone help me with implementing an auto scroll to each div or element when the user scrolls using the mouse? Here is the scenario:

Imagine this structure of the page...

<div id="main-wrap">

<div class="my-div-1">
    <p>here goes my content 1</p>
    <img src="/images/sample-1" alt="sample-1"/>

</div>

<div class="my-div-2">

<p>here goes my content 2</p>
<img src="/images/sample-2" alt="sample-2"/>

</div>

<div class="my-div-3">

<p>here goes my content 3</p>
<img src="/images/sample-3" alt="sample-3"/>

</div>

</div><!-- end of main-wrap id -->

-If each div has enough content to make the page long, and a user is viewing my-div-1, how can I automatically scroll to my-div-2 when they scroll down instead of through the whole div?

I hope that makes sense. Any advice on implementing this feature using JavaScript and JQuery would be greatly appreciated.

Thank you in advance for any assistance.

Answer №1

Check out this fiddle for what you need: http://jsfiddle.net/3qxhY/9/

You can find the plugin used in the code here (debounce/throttle plugin):

Code

// debounce/throttle plugin
(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);

// insert elements to be scrolled to here
divs = [$(".my-div-1"),$(".my-div-2"),$(".my-div-3")];

var lastScrollTop = 0; // update on each scroll to determine direction
var run = true;

$(window).scroll($.debounce(250, true, function () { // only runs once per scroll
  var st = $(window).scrollTop();
  if (st > lastScrollTop) { 
    $.each(divs, function (i, v) {
      ((v.offset().top - $(window).scrollTop()) < 0) && (next = i + 1);
    });      
    run = (next != divs.length) ? true : false;
  } else {
    $.each(divs, function (i, v) {
      ((v.offset().top - $(window).scrollTop()) < 0) && (next = i);
    }); 
    run = true;
  }
  if (run) {
    $('html, body').animate({
      scrollTop: divs[next].offset().top
    }, 1000,'linear', function() {
      lastScrollTop = $(window).scrollTop();
    });
  } else { lastScrollTop = $(window).scrollTop(); }
}));

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

When a panorama is entered in ThreeJS/Panolens, what is the orientation of the camera?

I want to use an equirectangular image with Panolens and achieve the same panorama viewer effect as seen in the links below: Even though Panolens.js is based on Three.js, I encounter a different result when I input my image compared to the first link abov ...

Interacting with my Rails API through JavaScript requests

Exploring the world of Rails and diving into creating a basic rails-api. Currently facing an issue while trying to incorporate user addition to my model using a JavaScript request... Let's take a look at my HTML file named add-user.html: <script ...

Is your Ajax jQuery live search not functioning properly with JSON data?

My programming code is not functioning properly. Here is the file I am working on. When it does work, it does not display the list and gives an error in the Json file. I am unsure of the reason behind this issue. You will be able to view the error in the C ...

Difficulty arises in designing a tableless layout due to the issue of auto

Wondering why my page is not expanding with its content? Check out my demo on Fiddle http://jsfiddle.net/msas3/. The light blue area should determine the overall height of the page. ...

Incorporating data types into a constant in Typescript/Javascript

Imagine I wanted to ensure these variables are string objects by adding a type string declaration to this variable assignment. What is the correct way to accomplish this? const { someID, someName, someAPIenvironment } = useParams(); This is what I attemp ...

Implementing a line break within a JavaScript function specifically designed for formatting images

As I am not a javascript developer, the code I have been given for debugging is somewhat challenging. The issue at hand involves an iOS module where a .js CSS file has been set up and images are loading improperly, resulting in the need for horizontal scro ...

Submitting form rows via Checkbox selection in PHP

After going through numerous questions, I noticed that most of them were focused on posting checkbox values. What I'm attempting to achieve is to only post the rows where the checkboxes are selected. The form contents are retrieved from a query of 3 ...

Ways to resolve issues with resizing div elements while waiting for JavaScript to load

Apologies for the lack of a clear title to describe my issue. My problem involves this snippet of code, where I am creating a label to show time to users. <div class="content"> <div class="container"> <div class="card"> < ...

The error message "404 Not found" is returned when attempting to retrieve a Google spreadsheet

I have exhausted all of my options on the web trying to retrieve my Google spreadsheet as a json file. $.getJSON() However, I am constantly receiving a 404 Not Found error. When I publish to the web, the URL I get is: https://docs.google.com/spreadsheets ...

Is there a way to specifically execute a Mongoose validate function solely for the create user page and not the edit user page?

Exploring Different Tools In the process of developing a website using Node.js, Express, and MongoDB. Leveraging mongoose for interacting with the MongoDB server has been quite beneficial. However, I encountered an issue where a function within my Mongo ...

Modifying the status of a link using jQuery

My ajax function handles two different outcomes based on the class of the link that is clicked. To avoid reloading the entire page when the link is clicked, I have utilized the following code: Everything seems to be working fine, however jQuery still rec ...

Express application (utilizing TypeScript) failing to handle routes efficiently

Encountering a technical issue : I am developing a REST API, but my application does not seem to trigger the actions when I send a request to the endpoint. This is my server configuration: import express, { Express } from 'express'; import c ...

How can MongoDB be used to query nested JSON structures?

My JSON data structure is as follows: "marks":{ "sem1" :{ "mark1":10, "total":100 }, "sem2":{ "mark2":20, "total":200 }, "sem3":{ "mark2":30, "total":300 } } I want to display the re ...

Anticipate feedback from Python script in Node.js

I have developed a website using nodejs and express, but I am facing an issue with integrating a python script for face recognition. The problem lies in the fact that when I invoke this script from nodejs using child-process, it takes around 10 to 20 secon ...

Can you help me troubleshoot my PHP upload script?

Today, I attempted to create a PHP upload script, but encountered an issue. The file is not getting uploaded and upon investigation, it seems like there's an error in the if(move_uploaded_file($_FILES['file']['tmp_name'], $target_f ...

Navigating through pages: How can I retrieve the current page value for implementing next and previous functions in Angular 7?

Greetings, I am a new learner of Angular and currently working on custom pagination. However, I am facing difficulty in finding the current page for implementing the next and previous functions. Can anyone guide me on how to obtain the current page value? ...

Issue encountered while retrieving values from JSON for the data table

I recently developed an application using a combination of React and Flask to display JSON data in a table format. While I can successfully see the data loaded in the console, I encountered difficulties in rendering it within the data table. The technologi ...

What is the best way to modify the text color within a Navbar, especially when the Navbar is displayed within a separate component?

First question on StackOverflow. I have a Next App and the Navbar is being imported in the _app.js file. import Navbar from "../Components/Navbar"; function MyApp({ Component, pageProps }) { return ( <> <Navbar /> ...

What technologies are utilized to create this price chart in the JavaScript visualization?

Does anyone know how this historical data price graph is created? I've heard of JS libraries like that can generate visualizations, but I'm not very familiar with JS. Any tips on how to create a similar visualization would be greatly appreciate ...

I recently implemented a delete function in my code that successfully removes a row, but now I am looking to also delete the corresponding data from localStorage in JavaScript

I have successfully implemented a delete function in JavaScript that deletes rows, but I also want to remove the data from local storage. This way, when a user reloads the page, the deleted row will not appear. The goal is to delete the data from local s ...