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

CSS changes triggered by JQuery are ineffective

Having trouble modifying the CSS of a class in my HTML file. I've been struggling with this for quite some time and can't figure out what I'm doing wrong. (I've already attempted multiple versions, but nothing seems to work) Here' ...

What is the proper way to define an element's style property in strict mode?

Assuming: const body = document.getElementsByTagName('body')[0]; const iframe = document.createElement('iframe'); iframe.src = protocol + settings.scriptUrl + a; iframe.height = 1; iframe.width = 1; iframe.scrolling = 'no'; ...

What is the best way to calculate the number of days between today's date and the end of the current month using Moment.js?

Here's the current code snippet I am working with: const moment = require('moment') const m = moment const currDay = m().format('D') const dayOfWeek = m().format('dddd') const daysInMonth = m().daysInM ...

What is the best way to ensure an image fills the entire space within a Bootstrap modal container?

I'm having some issues with my bootstrap modals that contain images. When the images are long vertically, a scrollbar appears which is not ideal. I tried to solve this by setting a max-height for the modal-content and making the modal-body (where the ...

Generate a vertical line that spans the entire length of the webpage in a vertical direction

Looking for a way to add vertical borders that span the entire webpage to some text? Check out this HTML snippet: <div id="vLine"> <h1>text</h1> </div> Here's the accompanying CSS: #vLine { height: 100%; width: 5 ...

Utilizing two imports within the map() method

I have been considering the idea of incorporating two imports within map() in my React code. This is how my code looks: {this.state.dataExample.map(item => ( <ItemsSection nameSection={item.name} /> item.dat ...

What exactly does the next() function do in NodeJS/SailsJS?

I recently came across a SailsJS tutorial where the next(); function was used for user authentication. However, I'm still unsure of its exact purpose. Can anyone provide clarification on this? ...

Postpone the appearance of a pop-up message, make it show up only once

Is it feasible to create a pop up that appears after 4 seconds and stays visible until the user interacts with the mouse? The pop up should not appear if the user scrolls before it shows. You can refer to the image for more details on the pop up box :) &l ...

The text box's word limiter is malfunctioning when writing code on a child page of the master

Encountering an unexpected problem that I never thought would happen. I wrote a word limiter code for a text box on a single page and it was working perfectly fine. The word limiter worked and the remaining words were displayed by a label named "remaining6 ...

What does the reportProgress function do in HTTP services with JavaScript?

Can someone explain the functionality of reportProgress in JavaScript, specifically when used with Angular Typescript? I am having trouble finding documentation on this. return this.httpClient.request<ProductResponse>('get',`${this.basePath ...

Handlebars does not support loading data into variables using Express

My NodeJS/Express application utilizes Handlebars for templates, and everything works smoothly except when attempting to display data retrieved from an Express API. The data is successfully fetched and can be viewed in the Chrome debugger. In the problem ...

Creating a visual that when clicked, reveals an enlarged version at a different location

Is there a way to make an image appear in a different location on the page when it's hovered over? I've searched online but couldn't find a solution using just HTML and CSS. Does anyone know how to achieve this effect? Image not hovered: ht ...

Having trouble configuring the sticky-footer correctly

Currently enrolled in a web development course on Udemy, I am facing an issue with the footer on my webpage. Even after setting its CSS position to relative, the footer overlaps the content when more data is added. However, removing this positioning causes ...

Using namespaces in Rails to encapsulate CSS styles

Is there a way to add namespaces to CSS within a Rails project? I have two pre-defined CSS files and two application layouts. I want the first layout to use one CSS file, and the second layout to use the other. However, both CSS files have styles for the ...

How can I automatically update the content of a specific Div element when the page is loading using the Ajax load() function

This is the HTML code I have: <body onload="fun1()"> <ul id="nav" class="nav" style="font-size:12px;"> <li><a href="#" id="m_blink" onclick="fun1()">Tab1</a></li> <li><a href="#" id="d_blink" onclick="f ...

Integrate buttons for increasing and decreasing with the `<select>` element in HTML

Apologies for what may seem like a trivial question, but I am truly stuck. Despite searching extensively, I cannot find how to create a basic HTML tag with increase and decrease buttons aligned to the right. Your assistance would be greatly appreciated. Th ...

jQuery not refreshing properly

I'm currently in the process of creating a script to switch the language on a website using PHP and Ajax/jQuery. I would like the page content to refresh without having to reload the entire page. So far, this is what I have come up with: $( "a[data-r ...

AJAX allows developers to declare variables within their code to

Here is a snippet of my JavaScript code: $(\"img.agree\").click(function() { var follow_id = $(this).attr(\"id\"); var user_id = $(\"img.user_id\").attr(\"id\"); $.ajax({ type: \"POST& ...

Is there a way for me to retrieve the element that is linked to the ng-disabled attribute?

Is there a way to access the element with the ng-disabled attribute inside the function without passing it as a parameter? Here is the HTML element: <input class="needsDisabling" ng-disabled="isFieldDisabled()" type="text"> The isFieldDisabled fu ...

Issue with Ajax submit button failing to pass ID

I am encountering an issue while trying to update data using bootstrap modal. When the CGridView selectionChanged event is triggered, it should call a function to display a modal dialog form and populate the form with the selected data. Below is my CGrid ...