What is the best method for navigating to the next div element with Javascript?

Currently designing a website filled with Divs set to 100% height. I am working on creating a button that, when clicked, smoothly scrolls to the next div on the page. Below is the snippet of code I have written to achieve this functionality:

$(".next").click(function() {
    $('html,body').animate({
        scrollTop: $(".p2").offset().top},
        'slow');
});
body{
  margin: 0;
  height: 100%;
}

.p1{
  height: 100vh;
  width: 70%;
  background-color: #2196F3;
}
.p2{
  height: 100vh;
  width: 70%;
  background-color: #E91E63;
}
.p3{
  height: 100vh;
  width: 70%;
  background-color: #01579B;
}

.admin{
  background-color: #B71C1C;
  height: 100vh;
  position: fixed;
  right: 0%;
  top: 0%;
  width: 30%;
  float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="p1">
  
</div>
<div class="p2">
  
</div>
<div class="p3">
  
</div>

<div class="admin">
  
  <button class="next">NEXT</button>
  
</div>

Answer №1

In order to successfully implement this functionality, you must first determine which div is currently being displayed. You can achieve this by assigning a class to the active element and then use the next() method to navigate through all elements.

It's also important to note the inclusion of a shared class, .p, on all elements in the example below. This not only helps streamline the CSS code but also simplifies DOM traversal.

$(".next").click(function() {
  var $target = $('.p.active').next('.p');
  if ($target.length == 0)
    $target = $('.p:first');
    
  $('html, body').animate({
    scrollTop: $target.offset().top
  }, 'slow');

  $('.active').removeClass('active');
  $target.addClass('active');
});
body {
  margin: 0;
  height: 100%;
}

.p {
  height: 100vh;
  width: 70%;
}
.p1 {
  background-color: #2196F3;
}
.p2 {
  background-color: #E91E63;
}
.p3 {
  background-color: #01579B;
}

.admin {
  background-color: #B71C1C;
  height: 100vh;
  position: fixed;
  right: 0%;
  top: 0%;
  width: 30%;
  float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="p p1 active"></div>
<div class="p p2"></div>
<div class="p p3"></div>
<div class="admin">
  <button class="next">NEXT</button>
</div>

Answer №2

Ensure each container has the same class name. Begin with the first element and on each click, target the next scroller element.

var f = $('.p1');
var nxt = f;
$(".next").click(function() {

  if (nxt.next('.scroller').length > 0) {
    nxt = nxt.next('.scroller');
  } else {
    nxt = f;
  }
  $('html,body').animate({
      scrollTop: nxt.offset().top
    },
    'slow');
});
body {
  margin: 0;
  height: 100%;
}

.p1 {
  height: 100vh;
  width: 70%;
  background-color: #2196F3;
}

.p2 {
  height: 100vh;
  width: 70%;
  background-color: #E91E63;
}

.p3 {
  height: 100vh;
  width: 70%;
  background-color: #01579B;
}

.admin {
  background-color: #B71C1C;
  height: 100vh;
  position: fixed;
  right: 0%;
  top: 0%;
  width: 30%;
  float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="p1 scroller">

</div>
<div class="p2 scroller">

</div>
<div class="p3 scroller">

</div>

<div class="admin">

  <button class="next">NEXT</button>

</div>

Answer №3

Here's a simplified version that seamlessly transitions to the first slide after reaching the last one. We are keeping track of the current slide using the variable currSlide, and updating it internally within the function.

To streamline the process, I assigned a slide class to each slide, enabling me to:

  • easily determine the total number of slides
  • optimize the CSS

let currSlide = 1;
const SLIDE_LENGTH = $('.slide').length;
$(".next").click(function() {
  currSlide = currSlide === SLIDE_LENGTH ? 1 : ++currSlide;
  $('html,body').animate({
      scrollTop: $(`.p${currSlide}`).offset().top
    },
    'slow');
});
body {
  margin: 0;
  height: 100%;
}

/* Avoid repetitive styles */
.slide {
  height: 100vh;
  width: 70%;
}

.p1 {
  background-color: #2196F3;
}

.p2 {
  background-color: #E91E63;
}

.p3 {
  background-color: #01579B;
}

.admin {
  background-color: #B71C1C;
  height: 100vh;
  position: fixed;
  right: 0%;
  top: 0%;
  width: 30%;
  float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slide p1"></div>
<div class="slide p2"></div>
<div class="slide p3"></div>

<div class="admin">
  <button class="next">NEXT</button>
</div>

jsFiddle

Bonus Update:

If you wish to include a previous button in the future...

let currSlide = 1;
const SLIDE_LENGTH = $('.slide').length;

function moveSlide() {
  currSlide = $(this).hasClass("next") ? ++currSlide : --currSlide;
  if (currSlide < 1) {
    currSlide = SLIDE_LENGTH;
  }
  if (currSlide > SLIDE_LENGTH) {
    currSlide = 1;
  }
  $('html,body').animate({
      scrollTop: $(`.p${currSlide}`).offset().top
    },
    'slow');
}

$(".prev, .next").on("click", moveSlide);
body {
  margin: 0;
  height: 100%;
}

/* Avoid repetitive styles */

.slide {
  height: 100vh;
  width: 70%;
}

.p1 {
  background-color: #2196F3;
}

.p2 {
  background-color: #E91E63;
}

.p3 {
  background-color: #01579B;
}

.admin {
  background-color: #B71C1C;
  height: 100vh;
  position: fixed;
  right: 0%;
  top: 0%;
  width: 30%;
  float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="slide p1"></div>
<div class="slide p2"></div>
<div class="slide p3"></div>

<div class="admin">
  <button class="prev">PREVIOUS</button>
  <button class="next">NEXT</button>
</div>

jsFiddle

Answer №4

If you're wondering how to achieve this in JavaScript, I'll provide a brief vanilla JS solution for scrolling:

var p = 1;
const container = document.getElementById('container');
var nextPage = function() {
  var topPos = document.getElementsByClassName('page')[p++].offsetTop;
  container.scrollTo({top: topPos, behavior: 'smooth'});
}

In the code snippet above, replace page with the class name you assign to the div elements you want to scroll to, like so:

<div id="container">
  <div class="page p1"></div>
  <div class="page p2"></div>
  <div class="page p3"></div>
</div>

If you need to scroll the entire browser window instead of just a container, switch

container.scrollTo({top: topPos, behavior: 'smooth'});

to

window.scrollTo({top: topPos, behavior: 'smooth'});

For example:

var p = 1;
var nextPage = function() {
  var topPos = document.getElementsByClassName('page')[p++].offsetTop;
  window.scrollTo({top: topPos, behavior: 'smooth'});
}

You can adjust the topPos offset to fine-tune the scrolling position as needed.

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

JavaScript and CSS Modal showing incorrect data

Currently, I am utilizing a Jinja2 Template within Flask to render an HTML document. The process involves passing a dictionary called "healthy_alerts" into the Jinja template. Below is a snippet of the dictionary (with sensitive values altered): healthy_a ...

Is there a specific minimum height that should be set for the equalHeight function to apply?

Despite trying everything, I can't seem to achieve the dreadful layout my designer has given me without using JavaScript! The issue lies with the positioning of the div #backgr-box, which needs to be absolutely positioned behind the #contenuto ( ...

What is the best way to add a value to a textbox?

Hey there, I have a question about inserting a jQuery value into my HTML code. I need some assistance with my HTML and jQuery code. Any help would be greatly appreciated! < script > $(document).ready(function() { $("#oroom").blur(functi ...

Encountered an issue while mounting Vue component that was attempting to loop through itself: Component could not be mounted due to

Struggling to solve this particular issue. I have a primary wrapper element that utilizes another element to display the navigation structure. The navigation can have multiple levels, so it needs to be dynamically generated. This is how the wrapper looks ...

I'm unable to modify the text within my child component - what's the reason behind this limitation?

I created a Single File Component to display something, here is the code <template> <el-link type="primary" @click="test()" >{{this.contentShow}}</el-link> </template> <script lang="ts"> imp ...

Is there a way to extract an array from a property value within an object using JavaScript?

Here's the code snippet under consideration: var structures = { loginStructure : function(){ return structure = [ '<form name="',opts.formClass,'" class="',opts.formClass,'" method="post" action=" ...

Tips for parsing a JSON object efficiently

Javascript var obj = { "name" : ["alex","bob","ajhoge"], "age" : [30,31,33] }; To display the value "alex," you can use: document.write(obj["name"][0]) But how can we filter through 'obj' to retrieve all data like this? html <ul ...

Tips for showcasing boxed numerical characters on a website

Currently, I am tackling a project that involves converting a PDF into HTML. The original .ai file shows some numeric characters inside a box: https://i.sstatic.net/dAMU2.png Even though I am aware that the font used in the file is GothicMB101Pro DeBold- ...

Can a VS Code theme extension be designed using JavaScript or TypeScript rather than JSON?

Currently working on a VS Code theme extension, I am interested in exploring the possibility of using JavaScript or TypeScript files instead of a JSON file. The idea of having all the theme information crammed into one massive JSON file feels disorganize ...

What is the best way to apply different styles to alternative children within a dynamically generated list?

I am currently implementing the following code snippet: $('.js-toprow:nth-child(even)').css("background:", "#ddd"); $('.js-toprow:nth-child(odd)').css("background:", "#ff0000"); Within the function: function resetSlides() { conta ...

PHP code to display or conceal tables

I am facing a challenge in my PHP code where I need to hide a table based on a specific condition. Despite trying to use CSS for this purpose, it seems that CSS does not recognize the if condition and always overrides it. I am looking for a solution that ...

Tips for utilizing external data sources in React-Native collapsible/accordion components

Incorporating the react-native collapsible/accordion feature into my project has been a great addition. Below is an example I came across: import React, { Component } from 'react-native'; import Accordion from 'react-native-collapsible/Acco ...

Attempting to save data to a .txt file using PHP and making an AJAX POST request

I have been facing an issue while trying to save a dynamically created string based on user interaction in my web app. It's just a simple string without anything special. I am using ajax to send this string to the server, and although it reaches the f ...

Error: Unrecognized HTML, CSS, or JavaScript code detected in template

I'm currently utilizing the "Custom HTML Tag" option in GTM with my code below, but encountering an error when attempting to publish: Invalid HTML, CSS, or JavaScript found in template. It seems that GTM may not support or recognize certain tag attri ...

Obtain the closest numerical range using JavaScript

I have a range object and an array of price values. My goal is to find the nearest range from the range object for each value in the price values array. I attempted the solution below, but it did not give me the correct range. range = { 0: '25-500 ...

Best practices for efficiently utilizing setInterval with multiple HTTP requests in NodeJS

Imagine you have a collection with 3 to 5 URLs. You want to send requests every 5 seconds, one by one. Here is how I approached this: setInterval(() => { array.forEach(element => { request .get(element.url) .on('response', ...

What are the steps for converting a structured text document into a SQL table?

I am currently working on a project that involves the need to save and load a structured text document, similar to MS Word, into/from a MySQL table. For instance, if given a sample document like sample.doc, the goal is to save both the content and formatt ...

Verify whether the current location is within the circle

I am conducting a test to determine if my current location falls within a given radius of 300m. If it does, return true; otherwise return false. Below is the code I am currently using: <body> <button onclick="getLocation()"> ...

Using curly brackets as function parameters

Can someone help me understand how to pass an emailID as a second parameter in curly braces as a function parameter and then access it in AccountMenuSidebar? I apologize for asking such a basic question, I am new to JavaScript and React. class Invoices ex ...

What is the best approach to implementing a filter in Vue 2 that is also compatible with Vue 3?

Currently, I am utilizing Vue.js 2+ version and have implemented a date formatting filter to meet my needs. However, I recently found out that Vue 3 has removed the filter functionality in favor of using computed properties or methods. My dilemma now is ho ...