Modify vanilla JavaScript carousel for compatibility with Internet Explorer

I am currently in the process of creating a website that incorporates a carousel similar to the one found at the following link:

https://codepen.io/queflojera/pen/RwwLbEY?editors=1010

At the moment, the carousel functions smoothly on opera, chrome, edge browsers but encounters issues on Internet Explorer (IE). I am in need of a solution that will allow the carousel to function properly on IE as well. Any insights or workarounds would be greatly appreciated.

//I am uncertain about the cause of the issue on IE with this code
//     Identify the carousel to manipulate and the buttons to add events to
const carousel = document.querySelector("[data-target='carousel']");
const card = carousel.querySelector("[data-target='card']");
const leftButton = document.querySelector("[data-action='slideLeft']");
const rightButton = document.querySelector("[data-action='slideRight']");

// Set up limitations on the carousel sliding direction 
// and define how much the carousel should move each time.
const carouselWidth = carousel.offsetWidth;
const cardStyle = card.currentStyle || window.getComputedStyle(card)
const cardMarginRight = Number(cardStyle.marginRight.match(/\d+/g)[0]);

const cardCount = carousel.querySelectorAll("[data-target='card']").length;

let offset = 0;
const maxX = -((cardCount) * carouselWidth +
(cardMarginRight * cardCount) -
carouselWidth - cardMarginRight);


// Add click events
leftButton.addEventListener("click", function() {
if (offset !== 0) {
offset += carouselWidth + cardMarginRight;
carousel.style.transform = `translateX(${offset}px)`;
}
})

rightButton.addEventListener("click", function() {
if (offset !== maxX) {
offset -= carouselWidth + cardMarginRight;
carousel.style.transform = `translateX(${offset}px)`;
}
})
.wrapper {
height: 200px;
width: 632px;
position: relative;
overflow: hidden;
margin: 0 auto;
}

.button-wrapper {
width: 100%;
height: 100%;
display: flex;
justify-content: space-between;
align-items: center;
position: absolute;
}

.carousel {
margin: 0;
padding: 0;
list-style: none;
width: 100%;
display: flex;
position: absolute;
left: 0;
transition: all .5s ease;
}

.card {
background: black;
min-width: 632px;
height: 200px;
display: inline-block;
}

.card:nth-child(odd) {
background-color: blue;
}

.card:nth-child(even) {
background-color: red;
}
<div class="wrapper">
  <ul class="carousel" data-target="carousel">
    <li class="card" data-target="card">1</li>
    <li class="card" data-target="card">2</li>
    <li class="card" data-target="card">3</li>
    <li class="card" data-target="card">4</li>
    <li class="card" data-target="card">5</li>
    <li class="card" data-target="card">6</li>
    <li class="card" data-target="card">7</li>
    <li class="card" data-target="card">8</li>
    <li class="card" data-target="card">9</li>
  </ul>
  <div class="button-wrapper">
    <button data-action="slideLeft">L</button>
    <button data-action="slideRight">R</button>
  </div>
</div>

Answer №1

Invalid character

carousel.style.transform = `translateX(${offset}px)`;

Template literals (backticks) are not supported in IE

To resolve this issue, use

carousel.style.transform = "translateX("+offset+"px)";

Another error encountered is

Unable to get property '0' of undefined or null reference

This is due to auto being returned in IE

const cardMarginRight = Number(cardStyle.marginRight.match(/\d+/g)[0]);

To fix this, modify the code as follows:

const marginRight = cardStyle.marginRight;
const cardMarginRight = isNaN(parseInt(marginRight)) ? 0 : Number(cardStyle.marginRight.match(/\d+/g)[0]);

//It is unclear what is causing the IE issue in this code
//     Select the carousel you will manipulate and the buttons you will add events to
const carousel = document.querySelector("[data-target='carousel']");
const card = carousel.querySelector("[data-target='card']");
const leftButton = document.querySelector("[data-action='slideLeft']");
const rightButton = document.querySelector("[data-action='slideRight']");

// Set limitations on the carousel slide direction and control the sliding distance
// To show only three cards in the carousel view, the carousel width and the card margin are required
const carouselWidth = carousel.offsetWidth;
const cardStyle = card.currentStyle || window.getComputedStyle(card)
const marginRight = cardStyle.marginRight;
const cardMarginRight = isNaN(parseInt(marginRight)) ? 0 : Number(cardStyle.marginRight.match(/\d+/g)[0]);

// Count the total number of cards
const cardCount = carousel.querySelectorAll("[data-target='card']").length;

// Define an offset property to dynamically update by clicking the button controls
// Also, set a maxX property to determine when the carousel reaches the upper limit
let offset = 0;
const maxX = -((cardCount) * carouselWidth +
  (cardMarginRight * cardCount) -
  carouselWidth - cardMarginRight);


// Add click events
leftButton.addEventListener("click", function() {
  if (offset !== 0) {
    offset += carouselWidth + cardMarginRight;
    carousel.style.transform = "translateX("+offset+"px)";
  }
})

rightButton.addEventListener("click", function() {
  if (offset !== maxX) {
    offset -= carouselWidth + cardMarginRight;
    carousel.style.transform = "translateX("+offset+"px)";
  }
})
.wrapper {
  height: 200px;
  width: 632px;
  position: relative;
  overflow: hidden;
  margin: 0 auto;
}

.button-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: absolute;
}

.carousel {
  margin: 0;
  padding: 0;
  list-style: none;
  width: 100%;
  display: flex;
  position: absolute;
  left: 0;
  transition: all .5s ease;
}

.card {
  background: black;
  min-width: 632px;
  height: 200px;
  display: inline-block;
}

.card:nth-child(odd) {
  background-color: blue;
}

.card:nth-child(even) {
  background-color: red;
}
<div class="wrapper">
  <ul class="carousel" data-target="carousel">
    <li class="card" data-target="card">1</li>
    <li class="card" data-target="card">2</li>
    <li class="card" data-target="card">3</li>
    <li class="card" data-target="card">4</li>
    <li class="card" data-target="card">5</li>
    <li class="card" data-target="card">6</li>
    <li class="card" data-target="card">7</li>
    <li class="card" data-target="card">8</li>
    <li class="card" data-target="card">9</li>
  </ul>
  <div class="button-wrapper">
    <button data-action="slideLeft">L</button>
    <button data-action="slideRight">R</button>
  </div>
</div>

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

"An issue with the setTimeout function in React is leading to the page constantly refreshing

My buddies and I are in the process of developing a React App. The main goal is to identify the currently logged-in user, then send a post request to fetch everyone in the same "room" as them and display this information on the app upon page load. However, ...

Extracting Data from Multiple Pages Using Python 3 without Changing URL

Recently, I delved into the world of web scraping and decided to try my hand at grabbing data from various websites. Currently, I'm focused on scraping information from the site - Using selenium, I've managed to extract longitude and latitude da ...

limited growth of float variable

I am utilizing CSS code to create column a and column b, using float in the code to dynamically expand column a as content is added to column b. However, this expansion is not occurring as expected. To see my code, please visit http://jsfiddle.net/hadinetc ...

Another option instead of using jQuery to retrieve the active element in the

My goal was to determine when the user is interacting with an INPUT or TEXTAREA element and set a flag variable to true during this engagement. Once the user clicks out of these elements, the flag should be set back to false. To achieve this, I utilized j ...

Extracting the content within an HTML element through parsing

I am looking to extract the content inside these two elements and store it in a string: source_code = """<span class="UserName"><a href="#">Martin Elias</a></span>""" >>> text 'Martin Elias' Could someone guide ...

"Internet Explorer naturally selects the submit button when users press the enter key to submit a

In my current application, I have implemented a form with a hidden button to address issues with the numeric keyboard on Android. Essentially, pressing enter or focusing on the invisible button will trigger form submission. Pressing enter works fine in Ch ...

Generate a distinct identifier for the select element ID whenever a new row of data is inserted into a table

Although my title accurately describes my issue, I believe the solutions I have been attempting may not be on the right track. I am relatively new to javascript and web development in general, so please forgive me for any lack of technical terminology. Th ...

Accessing data attributes using AngularJS

Trying to extract the data attribute from the following code: <button ng-click="EditPlayer(name, position, number, age)" id="btnEdit" class="btn btn-successes" data-playerid="{{player.id}}">Save</button> Within my angular controller: $scope. ...

What is preventing me from integrating angular-cookies into my application?

I'm struggling to resolve this issue where I can't seem to make it work. My aim is to integrate NgCookies (angular-cookies) into my application, but all I'm encountering are errors. This is what I currently have: JS files being included: ...

"Material-UI enhanced React date picker for a modern and user-friendly

Currently, I am utilizing the Date picker feature from Material UI. The code snippet responsible for implementing it is as follows: import { DatePicker } from 'redux-form-material-ui'; <Field name="birthDate" ...

Tips for detecting when a browser is closing in a web application that is integrated with a master page

Currently, I am working on a web application that uses a master page. I need to be able to detect when the user is closing the browser so that I can raise an event to clean up session variables. I attempted using the unload JavaScript event, but it seems ...

A more efficient method for tallying values within an object (JavaScript, React)

Is there a more efficient way to determine the count of items with a specific key/value pair in a React state? When the list is large, this method may become a bottleneck. To illustrate the question, consider the following simplified example: class App ...

Is it possible to have both Node.js and browser code in the same file using webpack, while ensuring that only the browser code is accessible and the Node.js code remains hidden?

I need to work with a file that contains both Node.js and browser code. It's crucial that the Node.js code remains hidden when running in the browser environment. Is it possible for Webpack to exclude specific sections of the code based on the enviro ...

How can you modify a button in Ionic 2 based on the login status, using a modal to redirect to a different page once authenticated?

I have a button on my main page that is supposed to display 'Log out' when the user is currently logged in, and 'Log in' when there is no active user session. Clicking on the login button opens a modal. After successful login, the user ...

Connecting Documents and Organizing Folders

Currently, I am immersed in a web project leveraging java/ jsp/ servlets/ html/ css within Eclipse Tomcat. At the core of this project, all files are nestled neatly within the WebContent folder. Within my jsp files, I have encountered an issue when trying ...

Pagination with composite queries in Firestore allows for efficient retrieval of

Currently I am attempting to paginate a composite index query, let size = data.length let lastElement = data[size-1].commentCount db.collection('user-content').orderBy('commentCount','desc').orderBy('likes', 'd ...

Error: The getter callback for the component `RNCSafeAreaProvider` must be a function, but it is currently undefined

After attempting to update my React Native app's dependencies using npm update, chaos ensued. To rectify the situation, I reverted back to the previous package-lock.json, deleted the node_modules folder, and re-ran npm i. Surprisingly, instead of res ...

Border provides spacing within a div using the box-sizing property set to border-box

I am facing an issue where I have a div with the class "outer" containing another div with the class "inner". Upon adding a 2px border to the "outer" div, padding is automatically applied in a way that appears as 1px padding on the top, left, and right sid ...

Encountered an issue while attempting to load the required module

I'm having trouble setting up Stripe for my app and getting errors when trying to implement the module. Typically, I would require the module at the top of the file in order to use it, but when I do this in the paymentCtrl file, it doesn't work a ...

Absolute positioned TD creates a gap upon being displayed

Hey there, I am facing an issue with a table I have. In each row (TR), the last TD element has a class called 'abs'. The style for this class is specified in the provided code snippet. Initially, this element is hidden. However, when you hover o ...