I would like to create a click event on a check box and add a CSS class. I can use "classList.toggle" to add and remove the a CSS class by clicking the button 2 times. This is what I would like to do. When I click the checkbox for the first, I would like to add "xyz" class and when I click the same check box, I would like to add "abc" class and remove the "xyz" class.
const openModal = document.getElementById('mark-as-gift');
const modalBg = document.querySelector('.addtnew');
openModal.addEventListener('click', openModalBtn);
function openModalBtn() {
modalBg.classList.add('menscart2');
}
Here is my startet JS code. Thanks for the help
you can use the toggle DOM method, or instead you can use a boolean can that will check whether the checkbox is checked or not. click here to go to the official MDN Docs
Code example of the toggle method:
var element = document.getElementById("myDIV");
element.classList.toggle("mystyle");
I hope it helped :)
Use DOM.className.split(' ').indexOf(yourclassname) to check inside class if it contains then remove it by call DOM.classList.remove(yourclassname), 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(`Class name this element have: ${modalBg.className}`)
}
.menscart2 {
width: 100px;
height: 100px;
background: blue;
}
<input id="mark-as-gift" type="checkbox" />
<div class="addtnew">Hello</div>
const openModalBtn = document.querySelector("yourButton")
const modalBg = document.querySelector('.addtnew');
const classes = ["xyz", "abc"];
let toggled = false;
openModal.addEventListener('click', openModalBtn);
function openModalBtn() {
modalBg.classList.add(classes[+ toggled]);
modalBg.classList.remove(classes[+ !toggled]);
toggled = !toggled;
}