Issue with scroll animation across multiple div elements

I am working on a project where I have two main divs, one with the id of "left-div" and the other with the id of "right-div". In the "left-div", there are multiple nested divs each with their own unique id. The overflow-y property of the "left-div" is set to scroll. On the other hand, in the "right-div", there are several buttons each with their own id. My goal is to make it so that when a button is clicked, the "left-div" automatically scrolls to display the specific div related to the button. I am using jQuery for this task. How can I achieve this functionality?

Below is the code snippet:

<div id="#left-div">
   <div id="div1"></div>
   <div id="div2"></div>
   <div id="div3"></div>
   <div id="div4"></div>
</div>

<div id="#right-div">
   <button id="btn1"></button>
   <button id="btn2"></button>
   <button id="btn3"></button>
   <button id="btn4"></button>
</div>

Answer №1

If you want to achieve a specific functionality, consider using the same class for both a div element and its corresponding button. When the button is triggered, you can target elements with that shared class and smoothly scroll to the first matching element.

$(document).ready(function() {
  $("button").click(function() {
    var currentElement = $(this);
    var commonClass = currentElement.attr("class");
    var matchedElements = document.getElementsByClassName(commonClass);
    $("html, body").animate(
      {
        scrollTop: $(matchedElements[0]).offset().top
      },
      2000
    );
  });
});
#div1 {
  background-color: red;
}
#div2 {
  background-color: yellow;
}

/* Additional CSS code */

#left-div {
  overflow-y: scroll;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- jquery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <!-- Bootstrap 4 JS -->
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
      integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
      crossorigin="anonymous"
    ></script>
    <!-- Bootstrap CSS -->
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
    />
    <link rel="stylesheet" href="./index.css" />
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-8">
          <div id="left-div">
            <div id="div1" class="element1">
              <!-- Content of div1 goes here -->
            </div>
            <div id="div2" class="element2">
              <!-- Content of div2 goes here -->
            </div>
            <div id="div3" class="element3">
              <!-- Content of div3 goes here -->
            </div>
            <div id="div4" class="element4">
              <!-- Content of div4 goes here -->
            </div>
          </div>
        </div>

        <div class="col-4">
          <div id="right-div">
            <button id="btn1" class="element1">Button 1</button>
            <button id="btn2" class="element2">Button 2</button>
            <button id="btn3" class="element3">Button 3</button>
            <button id="btn4" class="element4">Button 4</button>
          </div>
        </div>
      </div>
    </div>

    <script src="./index.js"></script>
  </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

Tips for aligning text in MUI Breadcrumbs

I am currently utilizing MUI Breadcrumb within my code and I am seeking a solution to center the content within the Breadcrumb. Below is the code snippet that I have attempted: https://i.stack.imgur.com/7zb1H.png <BreadcrumbStyle style={{marginTop:30}} ...

Removing an element in Vue.js

Can someone help me with a Vue.js issue I'm having? I'm working on a quiz and I want to add a button that deletes a question when clicked. Here's what I've tried so far: deleteQuestion(index) { this.questions.splice(index, ...

Purchase Now with Paypal Button

Just starting out with PHP and PayPal buttons! Important: Referring to Mysql items here. I'm attempting to set up an online shop, but I have a concern about PayPal "Buy Now" buttons. If a customer purchases an item, the website receives the money, b ...

What is the best method for sending a document to a web API using Ajax, without relying on HTML user controls or forms?

I have successfully utilized the FormData api to upload documents asynchronously to a web api whenever there is a UI present for file uploading. However, I now face a situation where I need to upload a document based on a file path without relying on user ...

Is it possible to submit a POST method without using a form?

I am looking to create a button that functions similar to the "Follow" buttons found on social networks. The challenge I face is that I need to refresh the page when the user clicks the button, as the content of the page heavily depends on whether the user ...

Invalid Jquery syntax: Anticipated an assignment or function call but encountered an expression instead

Here's a simple code snippet: _create: function () { var self = this; $("#Grid").on("click", ".Row", function () { $(self).hasClass('Expanded') && $('html, body').animate({ ...

Vertically Center Image in a Div

I have been struggling to center an image within a div, but all the usual methods like using margin: auto; do not seem to work. I have tried various popular techniques with no success. <style> /* Add a black background color to the top navigation ...

The div's height is not matching the CSS declaration as expected

In my HTML, I have a div called innerDetails which serves as a flex item with the following CSS properties: .cover { height: 100vh; width: 100%; } #screenCon ...

Discover the steps to download web page data using Objective-C while ensuring that JavaScript has finished executing

I attempted something similar: NSString *url = @"http://www.example.com"; NSURL *urlRequest = [NSURL URLWithString:url]; NSError *error = nil; NSString *htmlContent = [NSString stringWithContentsOfURL:urlrequest encoding:NSUTF8StringEncoding error:&e ...

Show a brief description alongside multiple post thumbnails

I have successfully uploaded multiple featured images to my WordPress website using the multiple post thumbnail plugin. Now, I want to showcase them all below the content along with their descriptions. While I have managed to display the main featured imag ...

Extracting information from ul li div elements and saving it in JSON format

I have been pondering this issue for the past few hours and haven't been able to find a solution. Essentially, I have a list structured like this <ul class="list"> <li class="user"> <div class="name">Name</div> ...

Extend the height of bootstrap 5.2.0 row/column to reach the bottom of the page

I'm having difficulty extending the left navigation section to reach the bottom of the page while remaining responsive. Despite trying various solutions like h-100, flex-grow, min-vh-100m self-align: stretch, nothing seems to solve the issue. Check o ...

Use jquery and json to automatically populate select fields based on specific threshold values when they are changed

Looking for guidance on using jQuery to dynamically populate four select fields based on a four-level JSON array for a webshop, depending on threshold values. I'm seeking help with dynamically changing the selects only if the given value is greater t ...

Is there a way to align this in a horizontal inline block?

I have this element and I would like it to display inline-block but horizontally. Currently, it is displaying as inline-block but vertically. Here is my HTML: <div class="ondisplay"> <div class="left-text"> <p&g ...

Solution for Organizing Tables

I've sourced data from various JSON API links and displayed it in a table. Currently, my code looks like this: <script src="js/1.js"></script> <script src="js/2.js"></script> Above this code is the table structure with <t ...

Establishing a boundary by incorporating a variable into a numerical value

Is there a way to adjust the margin-bottom of an element based on the height of the next() element plus 12px? I attempted the code below but it didn't yield the desired results. $("div.entry-content").css("margin-bottom", $(this).next().outerHeight() ...

Finding the Nearest Value in an Array

My code involves a changing total number that I need to match with the closest value in an array of numbers, returning the index of the matching person, which should be Mia Vobos. I am attempting to find two people whose scores add up to the same total or ...

Ways to filter and display multiple table data retrieved from an API based on checkbox selection in Angular 2 or JavaScript

Here is a demonstration of Redbus, where bus data appears after clicking various checkboxes. I am looking to implement a similar filter in Angular 2. In my scenario, the data is fetched from an API and stored in multiple table formats. I require the abili ...

A backend glitch is exposed by NextJS in the web application

Currently, I am utilizing Strapi for my backend and have created a small script to handle authorization for specific parts of the API. Additionally, I made a slight modification to the controller. 'use strict'; const { sanitizeEntity } = require( ...

Utilizing Fullcalendar 5 in conjunction with Angular: Embedding Components within Events

Recently, my team made the transition from AngularJS to Angular 12. With this change, I upgraded Fullcalendar from version 3 to version 5 and started using the Angular implementation of Fullcalendar: https://fullcalendar.io/docs/angular While navigating t ...