I'm trying to add multiple event listeners a UL
in javascript.
How can I create a condition to .preventDefault()
if one of my .card
elements has already been clicked?
const cd = document.getElementById('listDeck')
cd.addEventListener('click', flipFirst, false)
function flipFirst(e) {
if (e.target && e.target.nodeName == "LI") {
var firstMove = document.getElementById(e.target.id)
firstMove.classList.add('open', 'show')
console.log('first card was clicked')
e.currentTarget.removeEventListener('click', flipFirst);
}
}
cd.addEventListener('click', function(evt) {
if () {
//condition is true
//then prevent default
}
var secondMove = document.getElementById(evt.target.id)
secondMove.classList.add('open', 'show')
console.log('second card was clicked')
})
Quick solution would be to set a property on evt.currentTarget, which refers to the dom node that the handler is on.
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
A simple way to do it would be to just set a class to the li that was clicked.
function flipFirst(e) {
if (e.target && e.target.nodeName == "LI") {
var firstMove = document.getElementById(e.target.id)
firstMove.classList.add('open', 'show', 'wasClicked') // Add class if clicked
console.log('first card was clicked')
e.currentTarget.removeEventListener('click', flipFirst);
}
}
cd.addEventListener('click', function(evt) {
if (evt.srcElement.classList.contains('wasClicked') == true) { // check if it has the class
//then prevent default
}
var secondMove = document.getElementById(evt.target.id)
secondMove.classList.add('open', 'show')
console.log('second card was clicked')
})
Or set a boolean variable in javascript
const cd = document.getElementById('listDeck')
cd.addEventListener('click', flipFirst, false)
var isBtnClicked = false; // <-- Here is variable declared.
function flipFirst(e) {
if (e.target && e.target.nodeName == "LI") {
var firstMove = document.getElementById(e.target.id)
firstMove.classList.add('open', 'show')
console.log('first card was clicked')
e.currentTarget.removeEventListener('click', flipFirst);
}
}
cd.addEventListener('click', function(evt) {
if () {
//condition is true
//then prevent default
}
var secondMove = document.getElementById(evt.target.id)
secondMove.classList.add('open', 'show')
console.log('second card was clicked')
isBtnClicked = true; // <--- Here is the variable
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.