Discovering the clicked element using JavaScript: A complete guide

Let me start by saying that I have come across similar posts about tracking event listeners, but in my specific case, I am struggling to figure it out. While I am familiar with the event.target property, I just can't seem to make it work.

Here is a snippet of my code:

const taskListSection = document.querySelector('.task-list-section');
const taskListAddModal = document.querySelector('.task-list-add-modal');
const confirmTaskAddBtn = document.getElementById('add-list');
const cancelTaskAddBtn = document.getElementById('cancel-add-list');
const addTaskBtn = document.getElementById('add-task');
const titleInput = document.getElementById('title');
const descriptionInput = document.getElementById('description');
const timeInput = document.getElementById('time');

const clearUserInput = () => {
    titleInput.value = '';
    descriptionInput.value = '';
    timeInput.value = '';
};

const taskListAddModalHandler = () => {
    const taskList = taskListSection.querySelectorAll('li');
    taskListAddModal.classList.toggle('visible');
    addTaskBtn.classList.toggle('visible');
    taskList.forEach((list) => {
        list.classList.toggle('visible');
    });
    clearUserInput();
};
const confirmAddTask = () => {
    const newTask = document.createElement('li');
    const taskList = taskListSection.querySelectorAll('li');
    const titleInputValue = titleInput.value;
    const descriptionInputValue = descriptionInput.value;
    const timeInputValue = timeInput.value;
    
    if(titleInputValue.trim() === ''){
        alert('Please enter a title of your task!');
        return;
    }

    newTask.className = 'visible';
    newTask.innerHTML = 
    `<button  class="check-task">C</button>
    <button  class="remove-task">X</button>
    <h4>Title:</h4>
    <p>${titleInputValue}</p>
    <h4>Description:</h4>
    <p>${descriptionInputValue}</p>
    <h4>Time:</h4>
    <p>${timeInputValue}</p>`;

    taskListSection.append(newTask);
    taskListAddModal.classList.remove('visible');
    taskList.forEach((list) => {
        list.classList.add('visible');
    });
    addTaskBtn.classList.toggle('visible');
    clearUserInput();
};


addTaskBtn.addEventListener('click', taskListAddModalHandler);
cancelTaskAddBtn.addEventListener('click', taskListAddModalHandler);
confirmTaskAddBtn.addEventListener('click', confirmAddTask);
body{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.main-wrapper{
    width: 70rem;
    margin: 0 auto;
    border: 2px solid black;
    position: relative;
}
.main-wrapper #add-task{
    display: none;
}
.main-wrapper #add-task.visible{
    position: absolute;
    top: 150px;
    right: 100px;
    width: 50px;
    height: 50px;
    font-size: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
}
ul{
    border: 1px solid black;
    width: 40rem;
    height: 40rem;
    margin: 10rem auto;
    padding: 0;
    background-color: red;
    overflow-x: scroll;
}
ul form{
    
    flex-direction: column;
    width: 100%;
    height: 40rem;
    background-color: white;
    display: none;
}
ul form input[type=button]{
    display: block;
    margin: 10px auto;
}
ul form.visible{
    display: flex;
}
ul li{
    display: none;
}
ul li.visible{
    display: block;
    width: 80%;
    list-style: none;
    border: 2px solid black;
    margin: 10px;
    position: relative;
}
ul li .check-task{
    position: absolute;
    width: 30px;
    height: 30px;
    top: 30px;
    right: 30px;
}
ul li .remove-task{
    position: absolute;
    width: 30px;
    height: 30px;
    bottom: 30px;
    right: 30px;
}
ul li.checked{
    background-color: green;
}
<!DOCTYPE html>
<html lang="en>
...

(remaining text unchanged)

The issue I'm facing is tracking which 'C' button was clicked on which 'li' element. The desired functionality is that when the 'C' button on a certain 'li' element is clicked, I want THAT particular 'li' element to be assigned the class 'checked' (resulting in a green background). You create 'li' elements by clicking the "+" button at the top right corner, then filling in the input fields, and finally clicking the ADD button. Excuse the rudimentary design; it was created quickly for illustrative purposes. I'm seeking a solution using pure JS. Thank you in advance.

Answer №1

As requested, the example provided here is a simplified illustration of how you can incorporate an event parameter in your handler function to interact with the element triggering the listener. This demonstration aims to give you a basic understanding of the process, which can be easily implemented in your own code.

Additional details are highlighted in the code snippet below...

// Selecting all buttons in the document
let elements = document.querySelectorAll("button");

// Attaching an event listener to each button using a loop and a handler function for click events
for(let j = 0; j < elements.length; j++){
  elements[j].addEventListener('click', handleEvent);
}

// The handler function takes an "event" argument => e. 
// Using e.target allows us to identify the clicked element
// By utilizing a data attribute within the clicked element,
// we can locate its associated id and modify its background color accordingly
function handleEvent(e){
  let targetId = e.target.getAttribute("data-handler");
  let specificTarget = document.getElementById(targetId);
  specificTarget.style.backgroundColor = '#d4d4d4';
}
<div id="one">Div One</div>
<div id="two">Div Two</div>
<div id="three">Div Three</div>
<div id="four">Div Four</div>


<button data-handler="one">This button controls div one</button>
<button data-handler="two">This button controls div two</button>
<button data-handler="three">This button controls div three</button>
<button data-handler="four">This button controls div four</button>

Answer №2

My issue stemmed from the fact that my 'li' elements weren't predefined, unlike in your example. They were dynamically created using JavaScript, making it challenging for me to link a button with its corresponding li element and utilize the target property like you did with data-handler and the div element ID. However, I devised a solution by assigning a random ID to each li element generated through Math.random. Subsequently, I used this same ID as the data-handler value for the button, simplifying the process. Thanks for your guidance - it was just the nudge I needed to get everything working smoothly. Below is a code snippet that might prove helpful to others.

The provided JavaScript code snippet showcases how to create a task list functionality on a webpage. It includes event handlers for adding tasks, confirming tasks, and checking tasks. Additionally, it handles user inputs for title, description, and time of a task. The CSS code segment styles the appearance of the task list section and related elements.
The CSS styling for the task list interface enhances its visual presentation by defining the layout, colors, and positioning of various components. It ensures a clean and organized display of the task list items and associated buttons for checking and removing tasks.
The HTML structure outlines the main elements of the task list application, such as the add task button, task list section, form modal for adding tasks, and input fields for task details. This structure integrates seamlessly with the provided JavaScript and CSS to deliver a functional task management system.

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

Launching the node application using `node` as the starting command is successful, however, using `/usr/bin/node` as the starting

My goal is to configure a node application as a service. To start the service, I must initiate node with an absolute path, specifically using usr/bin/node. However, my application seems to malfunction when launched with this absolute path for unknown rea ...

What steps can I take to fix the Error with webpack's style hot loader JavaScript?

Just starting out with native script and encountered an issue when running this code: <template> <view class="container"> <text class="text-color-primary">My Vue Native Apps</text> </view> </template> &l ...

The Twilio JWT authentication token has expired

I'm currently utilizing Twilio voice call functionality and everything is working smoothly. However, the Twilio JWT token expires every hour, forcing users to refresh the page periodically. I'm seeking advice on how to extend the token validity p ...

Using JQuery to switch out images that do not have an ID or class assigned

Currently, I am using a Google Chrome Extension to apply an external theme to a website. Unfortunately, the logo on the site does not have an ID or class that can be used to call it. I am searching for a solution to replace it with a different image. My ...

What is the best way to ensure that all rows in flexbox have the same number and dimensions as the first row?

My objective with flexbox was to evenly distribute the text across the width of the page. When I say 'evenly distributed', I mean: If there are 3 sections, the center of the text in each section should be at fifths of the webpage width. This is ...

Exploring the Information Within HTML Forms

When my HTML form sends data to the server, it looks like this: { r1: [ '1', '2', '3' ], r2: [ 'Top', 'Greg', 'Andy' ], r3: [ 'validuser', 'invaliduser', 'validuser&a ...

Bootstrap 4: Popper not found - ReferenceError in the script

After setting up Bootstrap 4 using Node and Gulp, I encountered an error when running the application: Uncaught ReferenceError: Popper is not defined So far, I've only utilized the Bootstrap grid system and have not delved into the Bootstrap JS fu ...

What is the best way to deduct a variable's previous value from the final value, ensuring that the total value does not surpass a specific limit?

For instance: let num = 20; const sub = 6; const add = 10; num = num - sub; num = num + add; if (num > 20){ num = 20; } console.log("Only 6 was actually added to var num before reaching its maximum value"); Is there a way to adjust the console log ...

Showing local storage on a webpage using Jquery

I have encountered an issue where I can successfully add and remove items from local storage, but the added item does not display on my HTML page. The expected behavior is that when an item is added to local storage, it should be visible on a favorites pag ...

I'm having trouble getting CSS to apply to my HTML file. Any idea why?

I conducted tests in both Chrome and Firefox, ruling out any browser-related issues. My CSS has been validated and is error-free. However, when I validate my HTML code, an error message pops up stating "Bad value “stylesheet” for attribute rel on eleme ...

What is the best way to use jQuery to adjust the size of a slider image based on a percentage of the browser window

I've been searching all over for a solution to this issue, but so far I haven't had any luck. Basically, I have an image that is 1800 pixels wide by 500 pixels high. I need this image to adapt to all screen resolutions. Instead of having a fixed ...

Tips for creating a POST request using mongoose in NextJS version 13.4

Currently, I am faced with the challenge of executing a POST request using mongoose in NextJS. In my project structure, I have three key files: lib/dbConnect.js, models/User.js, and app/new/route.ts. As defined, app/new/route.ts is responsible for handling ...

The variation in CSS output between Google Chrome on Windows and Ubuntu

My code includes a div tag: <a href="#"><div class="field btn half green" id="register-btn">Register</div></a> Here is the CSS code for the tag: .field { position: absolute; width: 205px; left: 22px; color: #eaeae ...

Ways to create distance between two Table Rows in Material-UI TableRow

const useRowStyles = makeStyles({ root: ({ open }) => ({ backgroundColor: open ? "#F5F6FF" : "white", backgroundOrigin: "border-box", spacing: 8, "& > *": { height: "64px", ...

Unable to execute commitlint in husky along with a different custom command

Is it possible to set up two precommit hooks with husky? Specifically, I want to integrate commitlint along with a custom script specified in my package.json. After installing husky and creating a pre-commit script in the .husky folder, here is what I have ...

Displaying information stored in a database as notifications in the notification icon within the HTML/PHP header

Within my MySQL database, there exists a table named order_detail. This table is populated with values from my android app. I am looking to display the order_id as a notification in my admin panel, which is built using HTML/PHP. The attributes of the orde ...

A guide to customizing nested elements in react using styled-components

Currently, I am utilizing styled components to apply styles to a child element inside a div using nested css. For a demonstration, you can view my example here const customStyles = theme => ({ root: { ...theme.typography.button, background ...

Encountered a problem during the insertion of data into the database through ajax and php

An issue is being encountered while trying to insert data into a database using Ajax, PHP, and jQuery. The code works smoothly on a localhost environment, but upon uploading it to the server, an error occurs. $('#sunsubmit').click(function(){ ...

Troubleshooting Issues with AngularJS HTTP.get Requests

I'm currently working on a simple AngularJS application that is supposed to extract data from a .json file. While my code doesn't show any errors upon running it, it fails to retrieve the JSON values as expected. I have a feeling that I may be ov ...

Extracting information from CSS code

I am struggling to parse a RSS feed because all the information is contained within the description element. The CSS formatting makes it challenging to extract the actual strings. For example, below is a snippet of the description element: <table style ...