Guide on changing the background image of an active thumbnail in an autosliding carousel

My query consists of three parts. Any assistance in solving this JS problem would be highly appreciated as I am learning and understanding JS through trial and error.

https://i.sstatic.net/0Liqi.jpg

I have designed a visually appealing travel landing page, , featuring a thumbnail carousel powered by Glide.js, which functions smoothly with leftward movement and manual slide control buttons.

However, my attempt to implement a vanilla JS carousel slider has been unsuccessful after two days of struggling. The best I could achieve was getting a single carousel item to move both left and right. You can view it at .

I aim to have the carousel sliding automatically to the left, with arrow buttons for manual control of the slider.

To do this, I am targeting all carousel items using

querySelectorAll('.carousel-items')
and adding left:-274px to the carousel container glide__slides.

Below is my JS code:

// Variables & Event Listeners
document.querySelector(".left").addEventListener("click", slideLeft);

document.querySelector(".right").addEventListener("click", slideRight);

// Function to slide left
function slideLeft(left) {
  document.querySelector('.glide__slides').style.left = left;
}

// Function to slide right
function slideRight(right) {
  document.querySelector('.glide__slides').style.left = right;
}

Additionally, I want to create an active carousel item that automatically changes the background image when selected.

Currently, I am using hero.style.background = var; with an onclick event handler like onclick = function('01.jpg') on each carousel item to achieve this effect.

The following code accomplishes this feature:

// Change Hero Image
function heroChange(hmmm) {
  var hero = document.querySelector('.hero');
  hero.style.background = hmmm;
}

To improve the functionality, I plan to add EventListeners to the carousel items and apply an active class to the selected item. However, I need assistance with changing the background image accordingly.

Lastly, I have managed to incorporate content, backgrounds, and carousel indicators using multiple functions. While functional, the code seems overly complex as each .carousel-item invokes four functions. This structure needs refinement for better clarity.

If you can provide guidance on simplifying Part 2 & 3 by consolidating the functions into one and implementing automatic background image changes based on the active class, it would greatly aid my learning process.

JS offers a wide range of possibilities, and I hope to enhance my skills through your valuable insights. Your input will benefit not only this project but also several others in my portfolio.

An Update:

I have updated the slider implementation by utilizing margin-left adjustment suggested in this resource: vanilla javascript carousel not sliding.

// Variables & Event Listeners
document.querySelector(".left").addEventListener("click", slideLeft);
document.querySelector(".right").addEventListener("click", slideRight);

let marginLeft = 0;
const slides = document.querySelector('.glide__slides');

// Function to slide left
function slideLeft() {
  marginLeft += 264;
  slides.style.marginLeft = marginLeft + 'px';
  console.log(getComputedStyle(slides).marginLeft);
}

// Function to slide right
function slideRight() {
  marginLeft -= 264;
  slides.style.marginLeft = marginLeft + 'px';
  console.log(getComputedStyle(slides).marginLeft);
}

The carousel now moves manually, allowing sliding one item at a time. Nevertheless, I still seek assistance for the remaining issues:

  1. Implementing autosliding and looping at the end of the slides.

  2. Automatically updating the background when selecting an active slider instead of relying solely on onclick events.

  3. Streamlining the function calls and operations for a more organized code structure.

Answer №1

Exploring different approaches to streamline code and leverage native JavaScript functionality to create a continuous sliding effect is the core of this inquiry.

Initially relying on glider, a simpler alternative might prove effective, such as utilizing the animationend event for background transitions when a slide reaches the left side. Taking incremental steps to address the complex aspects of the code (part 3) is integral.

While the HTML structure appears intricate with four calls per li element click, its current configuration serves the purpose. The potential optimization lies in generating it dynamically at runtime for enhanced manageability. By modifying the slider array below, accommodating changes like removing or reordering slides becomes seamless through JavaScript automation.

The first aspect of the query pertains to sliding techniques. Employing CSS animations to shift the entire ul container showcases an example keyframe definition:

@keyframes sliding0 {
  0% { left: 0; }
  30% { left: 0; }
  100% { left: -33vw; }
}

A listener is added to capture animationend events on the element, signaling a switch in hero image once a slide completes its transition. Placing the vanished slide at the end ensures the infinite looping mechanism operates smoothly upon restarting the animation cycle.

For detailed event handling procedures and insights into implementing the changeHero function addressed in part 2 of the question, refer to the included snippet. It's noteworthy that the snippet functions reliably within the SO environment, though intermittent hiccups in hover actions may occur. Execution on a local machine should circumvent any issues.

<!DOCTYPE html>
<html>
<head>
// HTML, styles, and scripts elaborating on the slider creation and management process are encapsulated in this section.
</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

The texture appearance becomes unusual when using a ThreeJS point light

I utilized ThreeJS, specifically React Three Fiber, to construct a 3D Canvas. After adding a glb model, point light, and ambient light, the outcome was disappointing. https://i.sstatic.net/6vHaOKBM.png Why does the texture appear so jagged? Could it be ...

What is the significance of `()=>` in JavaScript when using Selenium?

What is the significance of () => in the following sentence? ()=>{Object.defineProperties(navigator,{webdriver:{get:()=>false}})} I have only seen this syntax in JavaScript and it seems to be used for configuring page evaluation with Selenium. T ...

Conceal a div containing a specific class during the page's loading process, then reveal it once the

Is there a way to hide a specific div class while a page is loading? Here is the structure I am working with: <div id ="container"> <div class="project-item tv"></div> <div class="project-item radio"></div> <div class="pro ...

Having trouble retrieving the URL from JSON data - every time I attempt to access it, it just shows as undefined. Any suggestions

Having trouble extracting the URL from JSON, as it shows undefined. Any suggestions? <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" ></meta> <script language="JavaScript" type="text/javascript" ...

Troubleshooting: AngularJS Http Post Method Failing to Execute

I am attempting to make an HTTP POST request to update my database using AngularJS. Although my code is not displaying any errors, the database is not being updated and I'm having trouble pinpointing the issue. Below is the code snippet: //topic-serv ...

The inability to destructure the 'store' property from the 'useReduxContext(...)' because of its null value

I am currently using NextJs 13 along with redux toolkit. Whenever I run the npm run build command, I encounter this error: "Cannot destructure property 'store' of 'useReduxContext(...)' as it is null." I suspect that the issue lies wi ...

What is the process of transforming an xhr request into an angular $http request?

I've been successfully loading images using ajax with the following code. However, when trying to convert it into Angular and use $http, it's not working as expected. Original ajax code var xhr = new XMLHttpRequest(); xhr.open('GET', ...

Occasional issue with Bootstrap where jQuery is required for JavaScript

Recently I have started implementing requirejs in my project, but I have encountered a persistent issue that I am unable to resolve. The error message "Bootstrap's JavaScript requires jQuery" randomly appears when I load my application. Below are the ...

Uncaught TypeError: Cannot create new instances of User - Node.js server not recognizing User as a constructor

I encountered an issue while attempting to save a user to MongoDB database using a post request. The error message "TypeError: User is not a constructor" keeps popping up despite the straightforward setup of my code. I have double-checked but can't se ...

Pass the array data stored in React state over to Node/Express

I have been exploring ways to transfer an array from my react front end to my node/express back end. Initially, I attempted the following method. In React: saveUpdates = (clickEvent) => { var list = []; var length = this.props.title.length; ...

What is the best way to generate a random item when a button is clicked?

I'm currently working on a feature in my component that generates a random item each time I access the designated page. While the functionality is set to automatically refresh and showcase a new random item, I am now looking to trigger this action man ...

Having trouble getting `sudo apt install npm` to work? You might be encountering the error message "The following packages have unmet dependencies

Creating dependency tree Retrieving status information... Completed Certain packages could not be installed. This might indicate that you have requested an unrealistic scenario or if you are utilizing the unstable version, some necessary packages could s ...

Implementing reCaptcha on React Native: A Step-by-Step Guide

Currently, I am in the process of integrating a reCaptcha validator into a login screen for a react-native application that needs to function seamlessly on both web and mobile platforms. Despite being relatively new to programming and lacking experience w ...

VueJS / v-html is displaying a blank page (Bokeh-html)

Especially as a newcomer to VueJS, I am currently in the process of trying to showcase a local HTML file within the Vue Application. The method I'm using to fetch the HTML file involves Axios, here's how it goes: <template> <div> ...

When navigating back, the Bootstrap Multistep Form breaks down

Tools I'm currently utilizing: HTML, CSS, Javascript, Bootstrap 3 Library / Package in use: https://codepen.io/designify-me/pen/qrJWpG Hello there! I am attempting to customize a Codepen-based Bootstrap Multistep Form from the provided link abov ...

Searching for a value within an array of objects using JavaScript: The ultimate guide

Similar Question: Locate specific object by id within a JavaScript objects array What is the best way to determine if a value exists in a given JavaScript array? For instance: var arr = [ {id: 1, color: 'blue'}, {id: 2, colo ...

Trouble with Jsonp when using the getJSON function in jQuery

$(document).ready(function() { $.getJSON("http://quanta.net16.net/wordpressnew/test.php?jsoncallback=?", function(data) { alert('swag'); }); }); This is the JSON request I'm making and my data is properly contained within ?({object} ...

Angular 2 - retrieve the most recent 5 entries from the database

Is there a way to retrieve the last 5 records from a database? logs.component.html <table class="table table-striped table-bordered"> <thead> <tr> <th>Date</th> <th>Logging ...

Vuetify - Implementing a search feature in a table that automatically navigates to the matching row

Currently, I am working with 2 Vuetify data tables that do not have pagination enabled. Each row in the second table corresponds to exactly one parent in the first table. My goal is to be able to click on an entry in the second table and have it automati ...

Angular Bootstrap: How to Resolve the Error "Function $(...).collapse() is Undefined"

I'm a beginner with Bootstrap and I'm attempting to trigger the .collapse() function using JavaScript within an Angular controller when a user clicks on a link. The goal is to close the collapsible navbar when a link is clicked, as the routing in ...