Conflicts in SwiperJS Timeline Management

Having a Timeline on my Website using SwiperJS presents challenges with conflicting functions. The goal is to navigate swiper-slides by clicking on timespans in the timeline.

The desired functionality for the timeline includes:

  1. Sliding to the corresponding slide when clicking on a timespan, setting it as active and scrolling it into view.

init: function () {
  const timeline = document.querySelectorAll(".timespan");
  timeline.forEach(function (timespan) {
    timespan.addEventListener("click", function () {
      // Remove active class from all timespans
      timeline.forEach(function (item) {
        item.classList.remove("active");
      });

      // Add active class to the clicked timespan
      timespan.classList.add("active");

      // Scroll to the clicked timespan
      scrollToTimespan(timespan);

      // Slide to the corresponding slide
      let slideIndex = parseInt(timespan.dataset.slideIndex);
      timelineSwiper.slideTo(slideIndex);
    });
  });
},

  1. Setting the middle timespan in the viewport as active. So when scrolling the timeline, the centered timespan becomes active and displays its related slide.

const timespans = document.querySelectorAll(".timespan");
const scrollContainer = document.querySelector(".about .container");
let scrolling = false;

// Function to check if an element is in the middle of the viewport
function isElementInViewport(element) {
  const rect = element.getBoundingClientRect();
  const viewportHeight =
    window.innerHeight || document.documentElement.clientHeight;
  const middleViewport = viewportHeight / 2;

  return rect.top <= middleViewport && rect.bottom >= middleViewport;
}

// Function to remove the active class from all timespan elements
function removeActiveClass() {
  timespans.forEach((timespan) => {
    timespan.classList.remove("active");
  });
}

// Function to set the active class to the timespan element in the middle of the viewport
function setActiveClass() {
  removeActiveClass();

  timespans.forEach((timespan) => {
    if (isElementInViewport(timespan)) {
      timespan.classList.add("active");
      const slideIndex = parseInt(timespan.dataset.slideIndex);
      timelineSwiper.slideTo(slideIndex);
    }
  });
}

// Function to scroll the timespan into view
function scrollToTimespan(timespan) {
  timespan.scrollIntoView({
    behavior: "smooth",
    block: "center",
    inline: "center",
  });
}

// Call the setActiveClass function initially on window load and on scroll
window.addEventListener("load", setActiveClass);
scrollContainer.addEventListener("scroll", function () {
  if (!scrolling) {
    scrolling = true;
    window.requestAnimationFrame(function () {
      setActiveClass();
      scrolling = false;
    });
  }
});

  1. Activating the corresponding timespan and scrolling it into view when dragging the swiper to the next or previous slide.

slideChange: function () {
      if (!this.isBeginning && !this.isEnd) {
        const timeline = document.querySelectorAll(".timespan");
        const activeSlideIndex = timelineSwiper.activeIndex;

        // Remove active class from all timespans
        timeline.forEach(function (item) {
          item.classList.remove("active");
        });

        // Add active class to the corresponding timespan of the active slide
        timeline[activeSlideIndex].classList.add("active");

        // Scroll to the corresponding timespan
        const activeTimespan = timeline[activeSlideIndex];
        scrollToTimespan(activeTimespan);
      }
    },

The above functions present conflicts, particularly with changing slides based on user interaction. Looking for suggestions on how to achieve the desired functionality mentioned.

Here is The code snippet:

Answer №1

Finally resolved the issue by implementing debounce on the scroll event.

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

Using the built-in http module in node.js to upload images via multipart/form-data

I have encountered an issue where I need to send two images and an API key as part of a multipart/form-data HTTP request to an API. The images are retrieved from an AWS S3 bucket, which works fine. However, when attempting to send the image data as part ...

Showing the computation outcome on the identical page

I have implemented a table within my PHP code. In the second column of this table, it typically displays "---". However, once I click the submit button, the same page should now display the calculated result. Here is an example: <table> <tr>& ...

Replacing values in an HTML file with MySql query results

----- Problem solved, solution below ----- In my HTML file, I have a dropdown menu for various courses listed as follows: <ul> <li class="dropbtn" id="1"> <a href="">first</a> <ul class="dropdown-content"> ...

Is there a way to trim the string after the second occurrence of an underscore?

I am faced with the task of extracting file names and types from a list of files in an object and displaying them in a table. The list of files is returned by the server in the format: timestamp_id_filename. For example: 1568223848_12345678_some_document. ...

Unusual behavior of middleware in express 4 causing a strange dynamic effect

I've encountered an issue where a dynamically created middleware in an Express 4 route is not getting called and causing a timeout. 'use strict'; var bodyParser = require( 'body-parser' ); var logger = require( './logger&apo ...

I am looking to enhance a button's appearance by applying CSS styling with a combination of two distinct flat colors

Is there a way to apply CSS styling to a button by incorporating two distinct flat colors? Specifically, I would like the left half of the button to be blue and the right half to be red. ...

Locate grandchildren elements using getElementById

My task is to modify the content and attributes of the table. The DOM structure is generated by a third-party tool, and I am using JavaScript to make changes in various sections. <div id="myId"> <div> <div> <table&g ...

Tips for effectively handling numerous iterations of an identical NPM dependency

Situation I have been working on creating various D3.js charts using the latest version of D3 (4.9.1). However, I also need to incorporate occasional C3.js charts into my application, which poses a challenge as C3 requires D3 v3.5.0. Exploring Options ...

Be mindful of potential missing dependencies when utilizing event listeners and states within useEffect

Whenever I utilize the addEventListener() method alongside trying to access some state within the useEffect, I consistently face the same issue. Adding the state as a dependency is not an option, as that would result in multiple event listeners being creat ...

"Explore the Hong browser designed specifically for enhanced Ajax functionality

I made the decision to revamp my new job by incorporating Ajax into the mix. Here is the code snippet I used to load pages: html <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <link rel="stylesheet" ...

The @Input decorator in Angular 2/4 is designed to only transfer fundamental values and not collections or complex data

I have encountered an issue while attempting to use @Input with a list of objects, where the @Input variable ends up being undefined. What is functioning properly can be seen in home.component.html: <p> <it-easy [mycount]="countItem" (result ...

The process of incorporating user properties into the output of a Service Bus topic from a Javascript Azure Function

I'm currently developing a TypeScript Azure Function that utilizes an Azure Service Bus topic as its output. Although I am able to send messages successfully, I have encountered difficulties in setting custom metadata properties for the message. In m ...

Unable to view cross domain cookies within the browser's development tools

I am currently working on a web application that has an Angular front end running on http://localhost:4200 and a NodeJs backend running on http://localhost:3000. When a user successfully logs in, a cookie is set from the backend containing a token. However ...

Retrieve the border color using Selenium WebDriver

Hey everyone, I'm currently trying to retrieve the border color of an extjs 4.2 form control text field using the getCssValue method. However, I'm having trouble getting the value as it's coming back blank. Below is a sample of my code that ...

Use JavaScript to dynamically generate a drop-down select menu

Is there a way to automatically expand a select menu dropdown using JavaScript or jQuery when a button is clicked? I am facing this challenge because I have a text field that allows users to input custom fields dynamically into a select input. My goal is ...

Is there a way to spin these hexagons around?

Hey there, I need some assistance with a problem. I have to rotate these three hexagons slightly, about 15 degrees or so. The catch is, it needs to work in Internet Explorer only. I've been struggling with this all day and it's getting ...

FixPermissions not working properly | Discord.js EXPERT

I am currently in the process of updating my bot to be compatible with the latest version of discord.js. I have successfully made various changes, but I am facing an issue with the overwritePermissions section within my ticket command. For some reason, the ...

Encountering a TypeScript error when using Redux dispatch action, specifically stating `Property does not exist on type`

In my code, there is a redux-thunk action implemented as follows: import { Action } from "redux"; import { ThunkAction as ReduxThunkAction } from "redux-thunk"; import { IState } from "./store"; type TThunkAction = ReduxThunk ...

The issue with color swapping in Internet Explorer is not functioning correctly due to

I am facing an issue with a jQuery script that I have created to change the background colors of rows in a large table. Unfortunately, it seems to be malfunctioning on Internet Explorer versions 6 through 9. Below is the snippet of code I am using: <s ...

Tips for incorporating animated features into a bar graph using jQuery

How can I create a dynamic animated bar graph using jQuery? I am looking to make the bar slide up from the bottom, incorporating images for both the bar and background. I have already set the positioning in CSS and now need to add animation to make the bar ...