Is there a way to create an automatic movement for the Slider?

I need assistance in getting my slider to auto-scroll. All the functionalities are working smoothly, but I'm struggling with making the slider move automatically. Below is a snippet of my code. Can someone please help me implement automatic scrolling where each photo transitions after 3 to 5 seconds? I've tried various methods, but they seem to mess up the responsiveness and positioning of the photos.

const menuBtn = document.querySelector(".menu-btn");
const navigation = document.querySelector(".navigation");

menuBtn.addEventListener("click", () => {
  menuBtn.classList.toggle("active");
  navigation.classList.toggle("active");
});

const btns = document.querySelectorAll(".nav-btn");
const slides = document.querySelectorAll(".img-slide");
const contents = document.querySelectorAll(".content");

var sliderNav = function(manual) {
  btns.forEach((btn) => {
    btn.classList.remove("active");
  });

  slides.forEach((slide) => {
    slide.classList.remove("active");
  });

  contents.forEach((content) => {
    content.classList.remove("active");
  });

  btns[manual].classList.add("active");
  slides[manual].classList.add("active");
  contents[manual].classList.add("active");
}

btns.forEach((btn, i) => {
  btn.addEventListener("click", () => {
    sliderNav(i)
  });
});
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700;800;900&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}

header {
  z-index: 999;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 200px;
  transition: 0.5s ease;
}

header .brand {
  color: #fff;
  font-size: 1.5rem;
  font-weight: 900;
  text-transform: uppercase;
  text-decoration: none;
  opacity: 0;
}

header .brand:hover {
  color: #14723d
}

header .navigation {
  position: relative;
}

header .navigation .navigation-items a {
  position: relative;
  color: #fff;
  font-size: 1.5em;
  font-weight: 900;
  text-decoration: none;
  margin-left: 30px;
  transition: 0.3s ease;
}

header .navigation .navigation-items a:before {
  content: '';
  position: absolute;
  background: #fff;
  font-weight: 900;
  width: 0;
  height: 3px;
  bottom: 0;
  left: 0;
  transition: 0.3s ease;
}

header .navigation .navigation-items a:hover:before {
  width: 100%;
  background: #14723d;
  font-weight: 900;
}

section {
  padding: 100px 200px;
}

.home {
  position: relative;
  width: 100%;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  flex-direction: column;
  background: #14723d
}

.home:before {
  z-index: 777;

...
</script>

Answer №1

const menuButton = document.querySelector(".menu-btn");
const navBar = document.querySelector(".navigation-bar");
const buttons = document.querySelectorAll(".nav-btn");
const images = document.querySelectorAll(".image-slide");
const paragraphs = document.querySelectorAll(".paragraph-content");
let currentSlideIndex = 0;
let slideIntervalId;

menuButton.addEventListener("click", () => {
    menuButton.classList.toggle("active");
    navBar.classList.toggle("active");
});

const navigateSlider = function(manual) {
    buttons.forEach((button) => {
        button.classList.remove("active");
    });

    images.forEach((img) => {
        img.classList.remove("active");
    });

    paragraphs.forEach((para) => {
        para.classList.remove("active");
    });

    buttons[manual].classList.add("active");
    images[manual].classList.add("active");
    paragraphs[manual].classList.add("active");
}

buttons.forEach((btn, i) => {
    btn.addEventListener("click", () => {
        navigateSlider(i);
        currentSlideIndex = i;
        clearInterval(slideIntervalId);
        restartAutoSlide();
    });
});

// Auto slide function
const autoSlide = () => {
    currentSlideIndex = (currentSlideIndex + 1) % images.length;
    navigateSlider(currentSlideIndex);
}

// Start auto slide
const startAutoSlide = () => {
    slideIntervalId = setInterval(autoSlide, 1000);
}

startAutoSlide();
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@200;300;400;500;600;700;800;900&display=swap');
/* CSS styles */
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sample Page</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <div class="brand">BRAND</div>
        <div class="menu-btn">
            <div class="navigation-bar">
                <div class="navigation-items">
                    <a href="#">ITEM</a>
                    <a href="#">ITEM</a>
                    <a href="#">ITEM</a> 
                    <a href="#">ITEM</a>
                    <a href="#">ITEM</a>
                </div>
            </div>
        </div>
    </header>
    <section class="home">
        <!-- Content goes here -->
    </section>
    <script src="main.js" defer></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

SEO tip: concealing lightbox images from search engines

Our website primarily uses lightboxes loaded via Ajax for images, meaning search engines may not index them when crawling the page. Is there a way to enhance SEO for these lightbox images? Thanks for your help! ...

Merge the throw new Error statement with await in a single expression

Is it possible to combine throwing an error and using the await keyword in one statement using the AND operator? The code snippet below demonstrates my intention: throw new Error() && await client.end(). So far, this approach has been working wel ...

Utilizing Ajax in conjunction with Ruby on Rails

I have a question that may be quite basic (I am new to Rails 3). I am looking to implement Ajax functionality where once a user clicks on a link, it triggers a $.post call and initiates some server-side changes. Within the _share partial file, I currently ...

In PHP, you can use the `echo` statement to output an HTML input

Incorporating HTML into PHP using heredoc methodology can sometimes lead to challenges when trying to retrieve user input variables. Attempting to access the input variable with $_GET["input"] may result in an error message indicating an undefined index: ...

Combine Woocommerce Product Bundles with Ajax Cart additions and the ability to continue shopping after adding items to your cart

I am currently working on implementing the functionality to add WooCommerce product bundles to my cart using ajax. Once the products are successfully added, I want two buttons to be displayed - one for viewing the cart and the other for continuing shopping ...

Can the combination of a JavaScript frontend and NodeJS backend function effectively together in this scenario?

I have a Domain-A that serves as a static site on Netlify, offering shopping cart functionalities. On the other hand, I have Domain-B hosting a backend server running a Node.JS payment system and utilizing Auth Services through passport.js. Due to its na ...

Having trouble retrieving data when updating a user in ExpressJS

Trying to update an experience array in the User model with new data, but facing issues with saving the data in the exec function. As a result, unable to push the new data to the array on the frontend. Here is the current code snippet: router.post('/ ...

Encountering an issue with an "unknown character encoding" error while using Firefox

Currently, I am going through the JS SPA book and have observed that I am encountering different outcomes while testing in Chrome as compared to Firefox. Here's the code snippet... <!doctype html> <html> <head> <title>SPA Ch ...

Refreshing a knockout observable following an asynchronous AJAX request by utilizing ko.mapping.fromJS

I am encountering an issue with updating data on the UI after making an asynchronous call to a web service and receiving JSON back. The JSON object that I receive has multiple properties, although only one is shown in the code snippet below for simplicity. ...

Convert the existing JavaScript code to TypeScript in order to resolve the implicit error

I'm currently working on my initial React project using Typescript, but I've hit a snag with the code snippet below. An error message is popping up - Parameter 'name' implicitly has an 'any' type.ts(7006) Here is the complet ...

Encountering an issue with eslint-loader in a new VueJS project: TypeError - eslint.CLIEngine is not recognized as

Embarking on a fresh VueJS venture with WebStorm. A brand new VueJS project has been established, NPM upgraded, Vuetify added, and upon server initiation, an error pops up: ERROR Failed to compile with 1 errors ...

Pentagon Silhouette as Header Background

I am looking to add a unique pentagon shape to my page header background without editing the HTML. I am using SASS for styling purposes. Is there a way to achieve a design similar to this wireframe image of a pentagon with the middle point at the bottom, ...

The combination of AddEventListener in the parent and postMessage in the iframe is ineffective

As I delve into the Stripe documentation to develop a new feature, I have encountered an issue regarding the communication between a webpage and an iframe. The code in index.html: <!DOCTYPE html> <body> parent<br> <iframe src="./ ...

I am struggling to run the jQuery animation that adjusts the width more than once

My goal is to allow the user to expand and retract a <div> element upon clicking. The desired behavior is for the <div> to expand when clicked, and then retract back to its original width when clicked again. However, when testing this function ...

Tips to prevent responseText from displaying Oracle errors when an insertion into the database fails

On my website, data is transferred from JavaScript to PHP. If the process goes smoothly, PHP should return a message like "user created successfully." However, in case of errors, it should only display "user could not be created" or "username already exist ...

"Troubleshooting cross-domain issues with iframes in Internet Explorer

My application is built with angularjs and we offer the option to embed it on other websites. Everything works well in IE11, but when the application is iframed onto a different domain's website, it stops working. I've tried adding <meta htt ...

Is it possible to conceal the mapbox access token during the map initialization process?

I have successfully integrated the mapbox API to create an interactive map on my website. To ensure the security of my access token, I have set up a proxy to handle the API requests externally. However, I am facing a challenge when it comes to hiding the a ...

What is the best way to incorporate audio playback while browsing files on an HTML5 webpage with TypeScript?

<input type="file" id="soundUrl" (change)="onAudioPlay()" /> <audio id="sound" controls></audio> This is the HTML code I'm working with, and I'm looking to trigger audio playback after a user selects an MP3 file using TypeScrip ...

Best practices for managing JWT tokens on the front-end with fetch requests and secure storage methods

Currently trying my hand at development, I am working on a task manager app where I've implemented JWT tokens for verification. While I managed to make it work on Postman, I'm stuck on how to store the token in a browser and send it to the server ...

Modifying dropdown options in React does not trigger updates, and console.log statements may not align as expected

I'm struggling to understand why my modal isn't updating correctly. Despite trying different variations of useEffect, useMemo, and useCallback, I keep encountering the same issues but in different ways. The problem arises when a `Device` is selec ...