I have several HTML elements that represent tiles to be flipped on click. Each element has a container div, which holds two divs, one for the front and back of the tile.
<div class="flip-container" data-tile>
<div class="flipper">
<div class="front white">
<!-- front content -->
</div>
<div class="back blue">
<!-- back content -->
</div>
</div>
</div>
I have the animation worked out in CSS so the tiles "flip" on hover. So far so good. Now I am trying to change the classList of the "flip-container" on click, so that a different className will be called from my style sheet.
My problem is that my handleClick function is targeting only the inner-div "back-blue", and not the "flip-container" that is holding both divs.
const tileData = document.querySelectorAll('[data-tile]')
const flipContainers = Array.from(
document.getElementsByClassName('flip-container')
)
flipContainers.forEach((container) => {
container.addEventListener('click', handleClick, { once: true })
})
function handleClick(e) {
console.log('clicked')
const container = e.target
const currentClassColor = 'blue'
fixColor(container, currentClassColor)
}
function fixColor(container, currentClassColor) {
container.classList.add(currentClass)
}
I have tried querying the "flip-container" both by selecting the data tag and also by grabbing an array from the specific className. In both cases, the entire element is still grabbed, and the target of the click applies only to the inner div. I guess it makes sense why this happening, but is there a way I can access the container even if the click target is one of the inner divs?
What you want is probably e.currentTarget.
The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred and which may be its descendant.
https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget
If that doesn't work for your case, you will want to try e.currentTarget.parentNode
e.target is the div that was clicked, if you want the div that the event handler is attached to you can use the this keyword or e.currentTarget.
function handleClick(e) {
console.log('clicked')
// const container = this
const container = e.currentTarget
const currentClassColor = 'blue'
fixColor(container, currentClassColor)
}