Delete an element from an array while retaining the event listener

I'm facing a challenge with an array of items that have the same event listener attached to them. I need to remove a specific item from the array while preserving the event listener on it.

Adding the event listener separately is an option, but I was hoping for a more streamlined solution.

Check out this pen for a demonstration. The code snippet in question fails to remove focus from the third button as intended.

To provide further clarity, here is the relevant JavaScript code:

const buttons = [...document.querySelectorAll(".button")];
let dropButton;

for (let i = 0; i < buttons.length; i++) {
    buttons[i].addEventListener("click", function () {
        setTimeout(() => { buttons[i].blur(); }, 500);
    });
    
    if(buttons[i].classList.contains("drop")) {
        dropButton = buttons.splice(i, 1);
        i--;
    }
}

Your assistance is greatly appreciated :)

Answer №1

Even though the event listener remains connected, there is an issue with the handler when the "dropped" button is pressed. The problem arises from the handler attempting to blur the incorrect button because it references buttons[i] using an outdated index.

Here are three alternative solutions for your handler:

// Declaring the button as a constant within a closure scope
const b = buttons[i];
buttons[i].addEventListener("click", function () {
  setTimeout(() => {b.blur();}, 500);
})

or

// Utilizing the "this" context in the handler to target the button
buttons[i].addEventListener("click", function () {
  setTimeout(() => { this.blur();}, 500);
})

or

// Accessing the button through the event object's "target" key in the handler
buttons[i].addEventListener("click", function (event) {
   setTimeout(() => {event.target.blur();}, 500);
})

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

Exploring numerous choices within a multi-select "category" search bar (web scraping)

Looking to scrape data from this French website using Python and the bs4 library: the content is in french :) . Specifically interested in extracting all possible values of a multi-select search bar named 'TYPE DE BIENS'. This type of search bar ...

Unable to modify information retrieved from API. Error: Unable to assign to property that is set to read-only

Using an API call, I retrieve some data. getPosts(postRequest: PostRequest): void { this._postService.getPosts(postRequest).subscribe(result => { const postList = result as PostList this.posts = postList.posts }); ...

Switch modules based on user options

My goal is to process an array of image files. I have the option to select them randomly or one by one (queue) based on the configuration specified in the config.json. To start off, I create the processor and determine the appropriate image selection modu ...

Display a PDF in a <div> when the menu is clicked

I have a project where I am trying to load a PDF in the middle of my page, inside a div, upon clicking on buttons in a side menu located on the left. While I have been successful in loading the PDF in the div, I am facing issues with triggering this action ...

Sending a 2-dimensional array from JavaScript to the server using AJAX

My JavaScript code involves working with a 2D array. var erg = new Array(); for (var i in val) { erg[i] = new Array(); for (var j in val[i]()) { erg[i][j] = val[i]()[j](); } } However, I encountered an issue where only the 1D array ...

Different ways to pass a component as a prop and display it based on certain conditions?

I'm currently working on a component that takes an ID number, checks its existence in the database, and renders a component if it's found. I need assistance with structuring this logic properly. Any guidance would be greatly appreciated. function ...

Make Vuetify icons display properly while loading a page from the local filesystem

I have set up a vue project using vue cli 3 and integrated Vuetify v2.0.19. One of the requirements for my project is to be able to compile it into a single HTML file so that it can be downloaded and run offline in a phonegap app (specifically on Safari v ...

I find arrays to be quite challenging and often encounter difficulties in

Currently, I am working on creating a table that will display users' names, grades, and subjects. The table is meant to showcase only the grades of each user. To achieve this, I am using a foreach loop to generate subjects and fetch grades based on th ...

Using caret range and package-lock.json to acquire the most recent non-disruptive versions

I understand the purpose of package-lock.json, but I'm unsure about how the caret range works after adding this file. Let's say I have a package called my-module and I want to automatically receive all new non-breaking versions without manually ...

Executing multiple asynchronous function calls within a for loop using JavaScript

Developing a mini Instagram-like bot for checking. The bot operates by using an object that contains a list of users from a chat along with their Instagram usernames. The issue I am encountering is related to asynchronous calls within loops. The loop con ...

Challenges with adding the current date into a WebSQL database using JavaScript in WebSQL

Can anyone help me figure out why the data is not being inserted into WebSQL when using the current date and time for INSERT and SELECT statements? Here's the code I'm currently using: SETUP.. myDb.transaction(function(tr) { tr.executeSq ...

Form a triangle in order to prevent the inner content from spilling out

I'm currently attempting to design a triangle shape that prevents the inner content from overflowing while still allowing the inner content to be draggable. So far, I have experimented with various solutions such as polygons and canvas, but none of t ...

Javascript has ceased functioning on the current server, however it is operational on a different

Need a hand with this tricky issue. The company I'm with has its own website. I've been updating pages on the site for the past few days. After finishing my updates and trying to upload the site, all of a sudden, the JavaScript stopped working. ...

Utilize Vue.js 3 and InertiaJs to Retrieve Session Information in Laravel 9

I am currently working on my initial Laravel project, incorporating Vuejs for the frontend. One of the key features of my application is allowing a Super admin to log in as a User (impersonate). By clicking on the Impersonate Button, the word impersonate g ...

Is there a way to pass attributes to BufferGeometry in THREE.js without using ShaderMaterial?

I've been attempting to make a THREE.js example designed for version 58 compatible with the latest version of THREE.js. You can find the original example here. While I was able to resolve a few errors by simply commenting out certain code, one error ...

Include a hyperlink beside the title of a section

drupal block heading I want to include a clickable link beside the header of this block that directs users to more news. Initially, I tried using CSS pseudo ::after to append text and a logo. However, I encountered difficulty in adding a clickable link t ...

Error message: "Angular 2 queryParams is causing a 'does not exist on type' issue"

My Angular2 service is designed to extract parameters from a URL, such as http://localhost:3001/?foobar=1236. import { Injectable } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import 'rxjs/add/opera ...

How can I transform a string into hexadecimal in Lua?

Having experience with C/C++ but being new to Lua, I am facing a problem regarding sending a byte array through a socket. Specifically, my question is: I need to send a bytearray that includes the mac_address, string_length, and string. Here are the deta ...

Conceal Backup Image for Computer Viewing

I am currently working on a project for this website and have added an mp4 video as the background. However, I have run into an issue where the video does not play on mobile devices, so I have had to implement a Fallback Image. The problem is that upon l ...

Implementing ui-sref-active for intricate routing states

I have implemented the menu link using AngularJS and UI-Router. <li ui-sref-active="active"> <a ui-sref="dashboard" title="Dashboard"><i class="fa fa-lg fa-fw fa-home"></i> <span class="menu-item-parent">Dashboard</spa ...