Is there a way to undo the click event in Javascript?

Is there a way to revert back to the initial position after clicking?

I successfully changed the x icon to a + icon on click, but now I'm struggling to reverse that action. I've tried using MOUSEUP and DBLCLICK events, but they aren't ideal solutions. Also, if I use the CLICK event in =>firstLiI.addEventListener('click', start2); it overrides the initial logic.

const firstLiI = document.querySelector('li').children[0].children[0];

firstLiI.addEventListener('click', start1);
firstLiI.addEventListener('dblclick', start2);

//Event Handler
function start1(){
  firstLiI.classList.add('fa-plus');
  firstLiI.classList.remove('fa-remove');
}

function start2(){
  firstLiI.classList.remove('fa-plus');
  firstLiI.classList.add('fa-remove');

}

Answer №1

It is recommended to toggle classes like this:

const firstLiIcon = document.querySelector('li').children[0].children[0];

firstLiIcon.addEventListener('click', handleClick);

//Event Handler
function handleClick(){
  firstLiIcon.classList.toggle('fa-plus');
  firstLiIcon.classList.toggle('fa-remove');
}

Answer №2

When your button does not have the fa-plus or fa-remove icons and only has a placeholder text, you need to follow this logic for toggling the icons after the first click.

(To reverse this process, simply change .add to .remove and .remove to .add). That's all!

const firstLiI = document.querySelector('li').children[0].children[0];

firstLiI.addEventListener('click', start);

//Event Handler
function start(){
  if (!firstLiI.classList.contains('fa-plus')) {
    firstLiI.classList.add('fa-plus');
    firstLiI.classList.remove('fa-remove');
  } else {
    firstLiI.classList.remove('fa-plus');
    firstLiI.classList.add('fa-remove');
  }
}

If your button already has one of these icons rendered, you can use the simpler toggle function like this:

function start(){
  firstLiI.classList.toggle('fa-plus');
  firstLiI.classList.toggle('fa-remove');
}

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

The function initFoodModel is missing and causing issues as it tries to read properties of undefined, specifically attempting to read 'findAll'

myWishlist.js const { setupFoodModel } = require("../../model/FoodModel"); const { setupWishlistModel } = require("../../model/myWishlistModel"); const setupMyWishlistModel = async () =\> { try { const sequelizeConnection = awai ...

Incorporation of a dynamic jQuery animation

I'm a beginner in jquery and I'm attempting to achieve the following: I want each menu to collapse separately when the mouse hovers over it. The issue is that both menus collapse simultaneously! I know it's probably something simple, but I ...

JavaScript: Utilize MooTools to extract a string containing a specific class and then pass it through a parent function

I am facing a major issue and struggling to find a solution for it. My problem involves returning values, mostly strings, that I can utilize in various contexts. For instance, I need to verify whether something is 0 or 1 in an if/else statement, or insert ...

What is the method to access 'let' variables in the console of a developer tool?

When you open the Chrome devtool and enter the code snippet below: // The iife is irrelevant let r = (() => { return 2; })(); and then evaluate r, the output will be: r 2 Surprisingly, both window.r and globalThis.r return undefined. Although let is ...

When the initial image URL returns a 404 error, the ng-src path does not automatically switch to the alternative

I'm currently working on a webpage where I want to show an image only if the URL of that image is valid, using AngularJS. The challenge I'm facing is that ngIf only checks whether a value is null or not. So, even if the URL returns a 404 error, ...

The div layer is positioned above the flash object

I have successfully implemented a method where I position a div over a webpage containing a flash object. This absolutely positioned div has a high z-index and captures click events. The main goal is to trigger the click event on the div when the flash obj ...

Quick method for handling arrays to generate waveforms

I'm currently working on optimizing the code for my web application. While it functions, the performance is a bit slow and I am looking to make improvements: The main concepts behind the code are: The function retrieves the current buffer and conve ...

After removing an element from an array in Vue.js, how can we adjust its class to reflect the change?

Apologies for my lack of proficiency in English. I am eager to find a solution to resolve these issues. I am working on a todolist and encountering an issue where the class ('centerLine') continues to affect the next element after deleting an a ...

What is the best way to incorporate JQuery into html content retrieved through an ajax request?

In my jsp file, there is a div structured like this : <div id="response" class="response"></div> After triggering an ajax call to a servlet, the content of this div gets updated with the following elements : <div id="response" class="res ...

Tips on reversing a numeric value with scientific notation in nodeJS

Exploring the optimal method to reverse an integer (positive and negative) in NodeJS 12 without the need to convert the number to a string. This solution should also accommodate numbers written in scientific notation such as 1e+10, which represents 10000 ...

Javascript will not be utilized in version 3.8

I'm encountering a problem with the website . It seems like my javascript files are not functioning properly. I added them in the functions.php using wp_enqueue_script(). The browser inspector confirms that the correct files are being called, but the ...

Can the order of React lifecycle events be reliably predicted across different components?

Is there a clear documentation on the guarantees of React lifecycle order across separate components? For instance, if I have: <div>{ x ? <A /> : <B /> }</div> When x changes from true to false, one component will unmount and the ...

How to Enhance GraphQL Mutation OutputFields with a Function Generator

I'm encountering issues while trying to incorporate a function generator within a GraphQL mutation. The function generator is utilized to streamline the promise chain inside the mutation. Prior to refactoring the code, everything was functioning corr ...

Using Jquery to delete the parent element containing text that does not match

I need to search for text in a table cell that matches the text in an h1 heading and then eliminate all other table rows containing text that does not match. The code snippet provided only works if there is one .tablerow with a .tablecell, so I am looking ...

Issue with accessing container client in Azure Storage JavaScript library

When working on my Angular project, I incorporated the @azure/storage-blob library. I successfully got the BlobServiceClient and proceeded to call the getContainerClient method, only to encounter this error: "Uncaught (in promise): TypeError: Failed ...

What could be causing passport.authenticate to not be triggered?

After multiple attempts to solve my first question, I am still unable to find the answer. Maybe it's due to being a newbie mistake, but I've exhausted all my efforts. This is how I created the new local strategy for Passport: passport.use(new ...

Stopping JavaScript when scrolling to the top and running it only when not at the top

I found a great jQuery plugin for rotating quotes: http://tympanus.net/codrops/2013/03/29/quotes-rotator/ Check out this JSFiddle example: http://jsfiddle.net/LmuR7/ Here are my custom settings (with additional options that I haven't figured out yet) ...

Navigate to the following section on an HTML page by clicking a button using jQuery

Within my application using Jquery / Javascript, I am looking to implement a specific functionality. I currently have several div elements like the ones below: <div id="div1"></div> <div id="div2"></div> <div id="div3"></ ...

Activate DivMenu's second list item automatically

I've been trying to use the trigger function multiple times, but it just won't work. I need help with auto-triggering the menu of the second list element. Can someone please assist me? Here is a snippet of my code: $("document").ready(functio ...