What is preventing me from executing this function more than once?

Having this function:

const sliderTextChange = document.getElementsByClassName('slider') // text change

const changeSliderText = change => {
  const sliderLeft = document.getElementsByClassName('switch-left')
  const sliderRight = document.getElementsByClassName('switch-right')

  for (let i = 0; i < change.length; i++) {
    change[i].addEventListener('click', () => {
      sliderRight[i].style.display = 'flex';
      sliderLeft[i].style.display = 'none';
    });
  }
}

changeSliderText(sliderTextChange);

This represents one of the sliders present on the website:

<div class="flex-column">
  <h3>Text Colour</h3>
  <div class="slider">
    <div class="slider-back"></div>
    <div class="slider-circle"></div>
  </div>
  <h3 class="switch-left">White</h3>
  <h3 class="switch-right">Black</h3>
</div>

Although similar functions exist in my code, they are only executed once. Once I trigger the event listener, it doesn't work again.

Any insights into what might be causing this issue?

Answer №1

My approach was to streamline the code while maintaining a modular and reusable view using scope.

function adjustSlider() {
 const sliderList = document.querySelectorAll('.slider');
 [...sliderList].forEach((slider) => slider.addEventListener('click', () => {
    const left = slider.parentElement.querySelector('.switch-left');
    const right = slider.parentElement.querySelector('.switch-right');
    const leftDisplay = left.style.display || 'flex';
    const rightDisplay = right.style.display || 'none';
    left.style.display = rightDisplay;
    right.style.display = leftDisplay;
 }, false));
}

window.onload = adjustSlider;
<div>
  <button class="slider"> - SLIDER 1 - </button>
  <div class="switch-left">L</div><div class="switch-right">R</div>
</div>
<div>
  <button class="slider"> - SLIDER 2 - </button>
  <div class="switch-left">L</div><div class="switch-right">R</div>
</div>
<div>
  <button class="slider"> - SLIDER 3 - </button>
  <div class="switch-left">L</div><div class="switch-right">R</div>
</div>
<div>
  <button class="slider"> - SLIDER 4 - </button>
  <div class="switch-left">L</div><div class="switch-right">R</div>
</div>

The parameters in your function may not be the most intuitive choices, adding unnecessary complexity to the example.

We opted for querySelector for readability, but if speed is your priority, consider using getElementsByClassName, which also functions on any DOM element.

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

Expanding upon React Abstract Component using Typescript

Currently, I am in the process of building a library that contains presentations using React. To ensure consistency and structure, each presentation component needs to have specific attributes set. This led me to create a TypeScript file that can be extend ...

Tips for bringing in and adding an excel spreadsheet to a kendo grid with the help of JQuery

I am facing a challenge with my kendo grid as I am trying to incorporate an excel file into it. Specifically, I would like to import and add an excel file to my kendo grid. If, for instance, my kendo grid initially has 3 rows, after importing an excel file ...

Updating variable storage in React components

This is a project built with Next.js and React. Below is the folder structure: components > Navbar.js pages > index.js (/ route)(includes Navbar) > submitCollection.js (/submitCollection)(includes Navbar) The goal is to allow users to inpu ...

Crafting dynamic parameters in the Express router - A step-by-step guide!

Original Code Example: const express = require('express'); const router = express.Router(); router.get('/data/:d1/:d2/:d3', require('../apifoo').foo); Route: /data/:d1/:d2/:d3 Path: /data/1/2/3 req.params : 'd1' : ...

Create HTML content dynamically with JavaScript and then utilize AngularJS to interpret and render it

I am creating an HTML table that looks like this: <table id="#webappname"> <tr ng-repeat="data in d"> <td>1 {{data}}</td> <td>2 hey !</td> </tr> </table> To create this, I am using a ...

Is there a way to apply -webkit-line-clamp to this JavaScript content using CSS?

i have a random-posts script for my blogger website <div class="noop-random-posts"><script type="text/javascript"> var randarray = new Array(); var l=0; var flag; var numofpost=10; function nooprandomposts(json){ var total = ...

The JQuery command to set the display property to "block" is not functioning as expected

When trying to toggle the visibility of my TextBox based on a selected value in a RadiobuttonList, I initially wrote the following code: $("#<%= rbtnIsPFEnabled.ClientID %>").click(function () { pfno = $("#<%= txtPFNo.ClientID %&g ...

Even after trying to hide the legend in a Radar Chart using the configuration option `legend: {display: false}` in chart.js, the legend

Having trouble removing legend from Radar Chart in chart.js even when using legend: {display : false}. The code is being utilized and then displayed with HTML/JS. Here is the provided code snippet: var options5 = { type: 'radar', data: { ...

Refreshing the Mocha Server

Recently, I encountered a situation where I needed to automate some cleanup tasks in my Express server using Mocha tests. In my server.js file, I included the following code snippet to manage the cleanup operations when the server shuts down gracefully (s ...

What is the best way to manage user sessions for the Logout button in Next.js, ensuring it is rendered correctly within the Navbar components?

I have successfully implemented these AuthButtons on both the server and client sides: Client 'use client'; import { Session, createClientComponentClient } from '@supabase/auth-helpers-nextjs'; import Link from 'next/link'; ...

Optimizing File Transfers and Streaming Using Next.js and CDN Integration

As I work on developing a download system for large files on my website using Next.js and hosting the files on a CDN, I face the challenge of downloading multiple files from the CDN, creating a zip archive, and sending it to the client. Currently, I have i ...

Utilize Jasmine's AJAX spy to intercept and inspect the error request

I am encountering an issue while trying to monitor the ajax error request and receiving the following error message. Can someone assist me with this? TypeError: e.error is not a function Code snippet for JS testing : function postSettings() { $ ...

Utilizing titanium to develop a functionality that listens for button presses on any area of the screen

I am trying to simplify the action listener for 9 buttons on a screen. Currently, I have individual event handlers set up for each button, which seems inefficient. Is there a way to create an array of buttons and manipulate them collectively? For example ...

Navigating through history using the pushState method and incorporating back and forward buttons

I am trying to implement back and forward buttons functionality with this ajax method The code is working well, and the URL in the browser is changing as expected However, when I click on the back and forward buttons, nothing happens (function(){ ...

Graphical Interface for an HTTPAPI

After successfully building a REST API in Node.js using Express that includes queue functionalities, my next goal is to develop a web interface for this API. As a newcomer to JavaScript and Node.js, I would greatly appreciate any advice or guidance on ho ...

Issue in d3.js: bisector consistently returning zero

http://jsfiddle.net/rdpt5e30/1/ const data = [ {'year': 2005, 'value': 771900}, {'year': 2006, 'value': 771500}, {'year': 2007, 'value': 770500}, {'year': 2008, 'value&apos ...

What steps can be taken to prompt the layout to transition?

I have an element that sticks to the top based on the current scroll offset. The issue is that the layout doesn't update when there is space available after the stuck element. This creates a ghost gap where the stuck element used to be... http://fidd ...

Create an array using modern ES6 imports syntax

I am currently in the process of transitioning Node javascript code to typescript, necessitating a shift from using require() to import. Below is the initial javascript: const stuff = [ require("./elsewhere/part1"), require("./elsew ...

Sending an array object from Ajax to Django Framework

AJAX Script Explanation: Let's consider the variable arry1D contains values [0,1,2,3,4] $.ajax({ url: "{% url 'form_post' %}", type: "POST", data: { arry1D: arry1D, 'csrfmiddlewaretoken': tk }, ...

Monitoring changes to an array of objects in AngularJS within a Select tag using the ng-repeat directive

My goal is to monitor select tags using ng-repeat and disable the save button. My current setup includes: Initially, I will have three select boxes with values. The user must select at least one value from these boxes to enable the Save button. The u ...