Is there a way to combine two addEventListeners into one for a single click event?

preview of a to-do list app

I am faced with a situation where I have two addEventListeners, one to change the text color and another to change the circle color.

In Condition 1: When I click on the circle, both the text and circle colors are changed.

In Condition 2: The issue arises when I click on the text, only the text color changes while the circle does not change.

Is it possible for me to combine these actions into just one addEventListener linked to the circle, and disable clicking functionality for the text? Or is there a way to make the text behave as if I clicked on the circle?
GitHub Link
App Preview

let lists = document.querySelectorAll(".list-item");
let circles = document.querySelectorAll(".fa-circle");

// Clicking on the text
Array.from(lists).forEach((list) => {
  list.addEventListener("click", () => {
    
    list.classList.add("done");
  });
});

// Clicking on the circle
Array.from(circles).forEach((circle) => {
  circle.addEventListener("click", () => {
    
    circle.classList.remove("fa-regular");
      circle.classList.add("fa-solid", "fa-circle-check");
  });
});

Answer №1

It all depends on your specific needs. Also, have you had a chance to review your DOM tree structure? Is .list-item positioned as a parent of/ or a sibling to '.fa-circle'? If your goal is to trigger an event upon the user clicking anywhere on a list item, then you can utilize the parent element in this manner:

const listParents = document.querySelectorAll('.list-parent')

function handleItemClick(event) {
  const listParent = event.target
  
  const listText = listParent.querySelector('.list-item')
  const listCircle = listParent.querySelector('.list-circle')
  
  listText.classList.toggle('done')

  listCircle.classList.toggle('fa-circle')
  listCircle.classList.toggle('fa-regular')
  
  listCircle.classList.toggle('fa-circle-check')
  listCircle.classList.toggle('fa-solid')


  l 
}

Array.from(listParents).forEach(listParent => {
  listParent.addEventListener('click', handleItemClick)
})

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

Avoiding the use of if statements in Javascript

I've recently started learning Javascript and I'm facing an issue with my code. I want to create a functionality where clicking on an image on one page redirects you to another page and shows a specific div based on the clicked image. To achieve ...

Effortlessly add and manipulate multiple classes in a generic class using querySelectorAll and classList, eliminating the

I'm encountering an issue that requires me to repeatedly utilize querySelectorAll with Element.classList. Each time, I must convert the NodeList obtained from Element.querySelectorAll into an Array. Then, I need to iterate over the Array using a for ...

Troubleshooting issues with static serving in Express.js

I'm facing an issue while trying to apply a bootstrap theme to a file created using Jade. The error message indicates that it cannot GET the file. Main JavaScript code snippet: const express = require('express'); const app = express(); ap ...

Tips for modifying the background color of an individual page in Ionic 3 and above

https://i.stack.imgur.com/t2mDw.pngI am just starting with Ionic and I'm attempting to modify the CSS of a single page by changing the background color to something different, like green, for example. I know that I can make global changes, but in this ...

Difficulty in altering the background of an input box

I am attempting to design a textbox that changes its background color to green when the correct answer is submitted, and to red for an incorrect answer. Unfortunately, nothing is happening for either option. document.querySelector('form').addE ...

Creating an inverted curve or border-radius for a div element is a design technique that can add

I've been tackling a project that requires me to style the border of a div in an inverted manner. To achieve this, I'm limited to using only CSS and JS without any plugins. I've searched through various online resources and similar questions ...

Adjust the size of the image as needed in order to fit within a container of fixed

Is there a clever way to use CSS and/or JavaScript/jQuery to adjust the size of images only when necessary for them to fit within a fixed-height container alongside the remaining content? Upon reviewing the images in the 'new this week' and &apos ...

choosing a date from the UICalendar

Recently, I've started exploring Angular and I'm trying to incorporate a calendar feature using ui-calendar. So far, I've managed to display a basic calendar with some events on it. Now, my goal is to allow users to click on a specific day ...

What makes ngFor unique in Angular that allows it to not require keys like in Vue and React?

I recently delved into learning Angular a few weeks back. In Vue and React, we typically use a unique key when rendering an array of elements to optimize the rendering process, especially when there are changes in the elements' order or quantity. As a ...

html Comparison of Documents

My goal is to compare HTML documents to see if they have the same tags in the same arrangement, regardless of different inner text and attribute values. I am only interested in comparing the general tag structure, such as: <html> <head> </h ...

Prevent angular from being executed through a JavaScript function triggered by a button click

Here is a button: <button ng-click="deleteCompany(company.id)" class="btn btn-danger" onClick="return window.confirm('This will permanently delete the entity\n Are you sure you want to delete this post?'); "> <s ...

What is the best method for storing dynamic values and attribute labels in a state within a React.js application?

I am currently working with react js. On my single product page, I have an array of objects called attributes that I need to display in the user interface. Here is a preview of how it looks: https://i.sstatic.net/GttrD.png My goal is to retrieve and stor ...

Using the v-for directive to create sequential lists

I am struggling to display pairs of data from an object based on category using nested v-for loops. The object, categoryArray, contains entries such as {stage 1, red}, {stage 1, blue}, {stage 2, orange}, {stage 3, brown}, {stage 2, green. My desired displ ...

Secure the data by encrypting it in the frontend before decrypting it in the

How can I achieve the highest level of security in this situation? I have experimented with using the same public key for all users to encrypt data transmitted over HTTPS to my backend automatically. However, individuals could potentially intercept and d ...

Theme.breakpoints.down not being acknowledged by MUI breakpoints

The Challenge: Implement a hamburger menu to replace the navMenu on tablet and smaller screens After successfully compiling in VS code terminal, encountering an error in the browser: Error Message: TypeError: Cannot read properties of undefined (reading ...

New approach: AngularJS - Using nested ng-click events

Looking for a solution to a problem with my html code: <div class="outerdiv" data-ng-click="resetText()"> <div class="innerdiv" data-ng-click="showText()"> {{ text }} </div> </div> The outer div has an ng-click fun ...

Return true in an incorrect manner

Coderbyte Challenge 7 Need help with a function that checks if every letter in the string is bounded by '+' signs. The code provided seems to be returning incorrect results - it should return false for the input string below as 'k' is ...

personalized options for initiating and concluding html audio component

I am currently facing an issue with my html audio element that plays a track. The setup is quite straightforward: <audio controls loop="loop"> <source type="audio/wav" src="song.wav"> </audio> However, I need to create custom start ...

Is there a way to display the button solely when the cursor is hovering over the color?

When I hover over a particular color, I want the button to show up. However, instead of displaying the button only for that color, it appears for all the colors of the product. Also, the placement of the button on the left side means that if I try to hover ...

The Elusive Solution: Why jQuery's .css() Method Fails

I am currently facing an issue with my code that utilizes the jQuery .css() method to modify the style of a specific DIV. Unfortunately, this approach does not work as expected. To illustrate the problem, I have provided a simplified version of my code bel ...