Utilizing JavaScript to trigger a series of click events on a single button in order to

I am working on implementing a click event for a checkbox that will add and remove CSS classes using the "classList.toggle" method. Specifically, I want the checkbox to toggle between adding the "xyz" class on the first click, and then adding the "abc" class while removing the "xyz" class on the second click.

  const openModal = document.getElementById('mark-as-gift');
  const modalBg = document.querySelector('.addtnew');
  
  openModal.addEventListener('click', openModalBtn);
 
  function openModalBtn() {
     modalBg.classList.add('menscart2');
      
  }

That's where I currently stand with my JavaScript code. Any assistance would be greatly appreciated!

Answer №1

One way to check if a class is present in an element and remove it if it exists is by using

DOM.className.split(' ').indexOf(yourclassname)
followed by
DOM.classList.remove(yourclassname)
. Here's an example:

const openModal = document.getElementById('mark-as-gift');
const modalBg = document.querySelector('.addtnew');

openModal.addEventListener('click', openModalBtn);

function openModalBtn() {
if(modalBg.className.split(" ").indexOf("menscart2") >= 0) {
modalBg.classList.remove('menscart2');
} else {
modalBg.classList.add('menscart2');
}
console.log(`This element's current class name: ${modalBg.className}`)
}
.menscart2 {
width: 100px;
height: 100px;
background: blue;
}
<input id="mark-as-gift" type="checkbox" />
<div class="addtnew">Hello</div>

Answer №2

const showModalBtn = document.querySelector("modalButton")
const modalContainer = document.querySelector('.newModal');
const styles = ["style1", "style2"];
let isShown = false;

showModalBtn.addEventListener('click', showModal);

function showModal() {
    modalContainer.classList.add(styles[+ isShown]);
    modalContainer.classList.remove(styles[+ !isShown]);
    isShown = !isShown;
}

Answer №3

To make things simpler and tidier, consider changing the classes you're using to toggle a single class instead. You can use :not(.class) to select the element if it does not have the class.

const openModal = document.querySelector('.toggle');
const modalBg = document.querySelector('.modal');
  
openModal.addEventListener('click', openModalBtn);
 
function openModalBtn() {
  modalBg.classList.toggle('open');
}
.modal.open {
  background-color: green;
  color: white;
}
.modal:not(.open) {
  background-color: red;
  color: white;
}
<button class="toggle">Toggle</button>
<div class="modal">Modal</div>

If you need two classes but are indifferent about the "invalid states" where the element has none or both classes, you can simply do something like this:

  const openModal = document.querySelector('.toggle');
const modalBg = document.querySelector('.modal');
  
openModal.addEventListener('click', openModalBtn);
 
function openModalBtn() {
  modalBg.classList.toggle('open');
  modalBg.classList.toggle('closed');
}
.modal.open {
  background-color: green;
  color: white;
}
.modal.closed {
  background-color: red;
  color: white;
}
<button class="toggle">Toggle</button>
<div class="modal closed">Modal</div>

If handling invalid states is important to you, establish some guidelines on how to deal with them.

Answer №4

If you prefer, you can alternatively utilize a basic .toggle() function with your classList, similar to what you attempted in your original script:

const toggleModal = document.getElementById('toggle-modal');
const modalContent=document.querySelector(".modal-content");
  
toggleModal.addEventListener('click', toggleModalClasses);
 
function toggleModalClasses() {
 modalContent.classList.toggle('active');
 modalContent.classList.toggle('inactive');
}
.active {opacity:1}
.inactive {opacity:0}
<button id="toggle-modal">Toggle Modal</button>
<div class="modal-content active">This is the content of the modal.</div>

Answer №5

To enable toggling in the DOM, you have the option of using the toggle method or utilizing a boolean variable to determine if the checkbox is selected. Check out this link for more information from the official MDN Docs.

Here's an example showcasing the toggle method:

var item = document.getElementById("myItem");
item.classList.toggle("active");

Hopefully, that clarifies things for you :)

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

Jumping transitions in thumbnail images

Could you please visit I've noticed that when hovering over the thumbnails in the last column, the images jump a bit after transition, especially in Firefox. Do you have any suggestions on how to resolve this issue? ...

Gridsome server-side rendering encounters issues with Auth0 authentication when the window object is not defined

After successfully following the Auth0 Vuejs tutorial with Gridsome during development, I encountered a problem when trying to build using gridsome build. The build failed because window was undefined in a server context. I discovered some issues in the A ...

Implementing hashing with resumable.js

Looking for a way to include hashing in resumable.JS by utilizing the "fileAdded" event hook. Any suggestions on how to add hash to each chunk? ...

A guide on how to initiate a click event in Angular 5 using JQuery

I am trying to trigger a click event for each element based on its id, but it doesn't seem to be working. Below is the code I am using: ngOnInit() { this.getProductsLists(); } getProductsLists() { this.supplierService.getProductLists() .sub ...

"Exploring the new features of Node.js 14 with ECMAScript modules

When exploring Node's official documentation regarding its built-in support for ECMAScript modules, it is mentioned that There are different types of specifiers: ... Bare specifiers such as 'some-package' or 'some-package/shuffle&apo ...

How can we delay UI updates until API calls have finished processing a chunk of requests in Redux-Saga without affecting the responsiveness of the user interface?

function* fetchDataFromChunks(dataList = []) { const segmentedData = yield call(splitDataIntoChunks, dataList, 5); for (let chunk of segmentedData) { const requests = chunk.map(item => call(retrieveImageData, item._id, item.im ...

Transform the string by eliminating any spaces and new lines before converting it into a JSON object

I need assistance with converting the given string into a JSON object. Here is the string: {\"Warranty\": [ \n { \n \"Name\": \"test\", \n \"Type\": \"test2\", \n \"Months\": ...

"I'm encountering an issue with the discord.js module when I try to launch my bot using node. Any ideas on how

I encountered an unusual error with my Discord bot recently. It seems that discord.js crashes every time I try to run my bot: [nodemon] 2.0.12 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mj ...

What is the best way to submit your CSS feature suggestions?

Is there a designated platform for submitting CSS feature requests officially? I am interested in proposing the addition of an 'inset' keyword to the text-shadow property for creating inset text shadows. This enhancement seems consistent with th ...

Is it possible to upload numerous profiles into the MYSQL database using this WP template?

Apologies in advance if my question is unclear, but in simple terms, I am looking to automate the process of uploading hundreds of profiles and jobs to this WP template: The developer of this template has stated that it is not possible to do this through ...

NextJS configuration facing an issue with rewrite rules not functioning as intended

I have attempted to utilize a rewrite rule in the NextJS next.config.js file in order to redirect URLs containing '/lite' to '?amp=1', however, it does not seem to be functioning correctly in all scenarios. Below is the code from my ne ...

How can I efficiently retrieve the "value" of a cookie and store it in a .txt file using Python?

Seeking to automate certain requests, I am currently using selenium's get_cookie function to extract cookies from a website. The retrieved cookie data is returned as a dict structured like this: {'domain': 'website-name-here', &a ...

Error occurs when attempting to instantiate a class with parameters that do not match any available constructor signatures

I am attempting to encapsulate each instance of router.navigateByUrl within a class function, with the intention of calling that function in the appropriate context. However, I am encountering an error that states 'Supplied parameters do not match any ...

Create a configuration featuring filter options similar to Notion's functionality

The objective is to create a system that can establish certain constraints, similar to the way Notion handles filter properties. https://i.sstatic.net/plctW.png System A sets up the constraints and System C evaluates them, both using Typescript. However, ...

Content Security Policy directive violation: Chrome extension policy error occured due to refusal to execute inline event handler

I've been working on a chrome extension to perform a simple task, but I've hit a roadblock with one line of HTML code that's causing issues with setting the correct permissions. Despite my efforts, I'm stuck on what exactly needs to be ...

Customizing the appearance of two separate tables

I have a pair of tables that I want to style differently. Table 1 needs the images centered with no border, while table 2 should have text left-aligned with a border. Here is the CSS: table, th, td { border: 1px solid #999; border-collapse: colla ...

How can I relocate an object to a different position within THREE.JS?

I'm trying to figure out how to move one object to the position of another object. I found some suggestions online to use the TWEEN library, but I'm having trouble integrating it into my code. Any help would be greatly appreciated :) <scrip ...

The intricate dance between JAVA and HTML

Can Java be compatible with HTML and JS? Is it possible for them to cooperate without using JSP? In order to connect the WEKA function, we utilized Java code through a JAR file, but now we also require HTML and JS links for visualization. Is there an alte ...

Executing Javascript to populate a div element with content based on its CSS class

Is there a way to isolate my View (HTML & CSS files) within a controller like JavascriptCode/AJAX, so that upon page load, only the controller binds the data to a specific element such as a DIV based on its class? Do you think this is achievable? If so, ...

Is it possible for a property to be null or undefined on class instances?

Consider this TypeScript interface: export interface Person { phone?: number; name?: string; } Does having the question mark next to properties in the interface mean that the name property in instances of classes implementing the interface ca ...