What is the best way to create a button that can cycle through various divs?

Suppose I want to create a scroll button that can navigate through multiple div elements.

Here is an example code snippet:

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>

I know how to make the button scroll to a single div, but I'm struggling with making it scroll sequentially through multiple divs.

Below is the code for the scroll button:

<section id="scrolldownButton" class="button">
            <a href=""><span></span>Scroll</a>
</section>

$(function() {
           $('a[href*=#]').on('click', function(e) {
               e.preventDefault();
                   $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top}, 500, 'linear');
                        });
                });

Give it a try:

$(function() {
  $('a[href*=#]').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({
      scrollTop: $($(this).attr('href')).offset().top
    }, 500, 'linear');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
<div id="5"></div>

<section id="scrolldownButton" class="button">
  <a href=""><span></span>Scroll</a>
</section>

Answer №1

To make this work, assign a class to the current active element and then use next() to locate the element that will be scrolled to when the button is clicked next. If you reach the end of the elements to scroll through, simply return to the beginning. I included a generic content class to the div elements for better consistency. Give this code a try:

$(function() {
  $('a[href*="#"]').on('click', function(e) {
    e.preventDefault();
    var $target = $('.content.active').next('.content');
    if ($target.length == 0)
      $target = $('.content:first');
      
    $('.active').removeClass('active');
    $target.addClass('active');
      
    $('html, body').animate({ 
      scrollTop: $target.offset().top
    }, 500, 'linear');
  });
});
.content {
  height: 250px;
}

#scrolldownButton {
  position: fixed;
  top: 20px;
  right: 50px;
}

.active {
  background-color: #EEE;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="1" class="content active">1</div>
<div id="2" class="content">2</div>
<div id="3" class="content">3</div>
<div id="4" class="content">4</div>
<div id="5" class="content">5</div>

<section id="scrolldownButton" class="button">
  <a href="#">Scroll</a>
</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

modifying output of data when onchange event is triggered

I am struggling with creating an onchange event for my option box in which the users of a site are listed. I have two input boxes designated for wins and losses, but the output is not changing when I select a user from the list. What could be wrong with my ...

Are there any substitute proxy servers that are capable of bypassing CORS restrictions using local IP addresses?

Successfully bypassing CORS for AJAX requests to public IP addresses using proxy servers has been a game-changer. Is there a similar approach that can be utilized for local IP addresses when the server is hosted off-site? Unfortunately, I lack the abilit ...

Transferring JSON data through AJAX to a PHP backend

I have been working on a solution to convert a CSV file into JSON and then send it to BigCommerce using their REST API. Initially, I planned to use Javascript for the entire process, and everything was successful until I encountered issues with CORS when t ...

What is the process for saving an image from a Three.js canvas?

Can you provide tips on saving an image from a Three.js canvas? I'm having trouble making Canvas2Image work with Threejs. The issue seems to arise because the canvas object needs a div to be attached to before it is defined. Check out this resource ...

Learn the process of directing to a view in a jQuery AJAX call with Spring MVC

Below is the ajax call I am using: $.ajax({ type: "POST", url: contextPath +"/action", cache:false, dataType: 'text', data: {Id:Id}, success: funct ...

jquery activating the toggle function to switch between child elements

I'm facing a challenge where I can't use .children() in this scenario, as it won't work since the elements aren't technically children. Here's the snippet of HTML that I'm working with: <p class="l1">A</p> ...

What is the best way to incorporate TypeScript variables into CSS files?

In my Angular project, I am aiming to utilize a string defined in Typescript within a CSS file. Specifically, I want to set the background image of a navbar component using a path retrieved from a database service. Although I came across suggestions to use ...

Incorporating base Tailwind CSS colors with the daisyUI theme: A simple guide

For my NextJS project, I'm utilizing Tailwind CSS in conjunction with daisyUI. In my configuration file tailwind.config.js, I have it set up as follows: /** @type {import('tailwindcss').Config} */ /* eslint-env node */ module.exports = { ...

Guide to configuring a robust schema and validation with joi

Currently in the process of setting up validation using the joi package, encountering syntax-related issues along the way. The schema in place is simple, checking for a valid number and verifying if the ID exists in the database. export default router.pos ...

The data that has been retrieved is not currently displayed within the Vue table

I'm currently exploring js/vue and I'm attempting to retrieve data from an API. There's a field where the value is used to fetch data from the API based on that keyword. When I check the console log, I can see that the data is being received ...

Utilizing AngularJS filter method to populate data

Just beginning my journey with Angular js, I've got this snippet of code that is responsible for binding data to the div element, app.filter("myfilter", function () { return function (data, catName) { if (angular.isArray(data) && angular ...

Changing text color based on positive or negative value in JavaScript(React)

Greetings everyone! I'm currently working on a specific feature that requires the color of a value to change dynamically. If the value is above 0, it should be displayed in green; if below 0, in red; and if equal to 0, in orange or yellow. To achieve ...

What is the process for integrating TypeScript compiling into a JavaScript application?

My project includes a build.js file that is responsible for building the project. It has two main objectives: Compile .ts files and store them in a new directory. Create an asar archive containing the compiled files. Since typescript (or tsc) is availabl ...

The POST request did not yield an HttpResponse object; instead, it returned None

When I submit a selection from a dropdown form to views as a POST request, and then use this selection to query data from Django, I encounter an issue while trying to map Django models data to Highcharts following this approach. The error message "the view ...

Conceal a div element after initial visit

There is a button (B) that displays a menu (C) when clicked, and a pop-up (A) that also shows the same menu (C) when clicked. There are 4 tasks to accomplish here. 1) Clicking B reveals C. 2) Clicking A reveals C. 3) Clicking B hides A. 4) A should be hi ...

Accessing PHP parameters in JSP files can be accomplished by utilizing specific

The PHP code snippet below checks for a username and password match before redirecting to a JSP page. if($userName==$dbUserName&&md5($passWord)==$dbPassWord){ echo "<input name='username' type='hidden' value='$userN ...

A guide on efficiently inserting multiple rows containing JSON data into a MySQL database simultaneously using node.js

I'm facing an issue with inserting multiple values into columns simultaneously. Let's say I have JSON data consisting of two rows of information, and I want to insert both rows into my table at one go. My attempt looks like this: var data = [&apo ...

Creating a Jquery slider animation: step-by-step guide

I tried implementing a code example in jQuery, but I am struggling with achieving smooth transitions in my slides. The changes are happening too abruptly for my taste. How can I create animations that occur during the transition, rather than after it? f ...

Acquire the model from a field within an Angular Formly wrapper

I'm in the process of designing a wrapper that will exhibit the model value as regular text on the page. Once the mouse hovers over this text, it transforms into a Formly field, which works perfectly fine. However, I'm encountering an issue where ...

What could be causing issues with the JQuery .Resize() function?

I'm attempting to create a responsive layout where the content div adjusts itself when the user resizes the page. The top and bottom divs are static, so only the content div changes its size based on the page flow. $(window).resize(function() { v ...