I’m trying to make buttons such that only one is active at a time. But I can’t get it to work.
My HTML:
<button class="js-toggle" onclick="toggle()">Gaming</button>
<button class="js-music-toggle" onclick="toggle2()">Music</button>
<button class="js-tech-toggle" onclick="toggle3()">Tech</button>
My Javascript:
const btnElem = document.querySelector('.js-toggle')
const techBtn = document.querySelector('.js-tech-toggle')
const musicBtn= document.querySelector('.js-music-toggle')
function toggle() {
if (!btnElem.classList.contains('is-toggled')) {
btnElem.classList.add('is-toggled')
} else {
btnElem.classList.remove('is-toggled')
}
}
function toggle2() {
if (!musicBtn.classList.contains('is-toggled')) {
musicBtn.classList.add('is-toggled')
} else {
musicBtn.classList.remove('is-toggled')
}
}
function toggle3() {
if (!techBtn.classList.contains('is-toggled')) {
techBtn.classList.add('is-toggled')
} else {
techBtn.classList.remove('is-toggled')
}
}
2
Answers
Please use this code:
Code:
HTML:
JavaScript:
Try this,