Reputation: 125
How to stop bubbling on exactly the particula element of the list ul
?
In my case, it is <li>
first child element of ul
which has data-slide-id
argument I want to pull out?
My JS file:
onSlideClick() {
document.getElementsByClassName('slider__container')[0].addEventListener('click', (e) => {
e.preventDefault()
console.log(e.target)
})
}
EDIT: I was trying also:
onSlideClick() {
this.container[0].addEventListener('click', (e) => {
e.stopPropagation()
console.log(e.target)
})
}
In this scenario, when I click on list ul I get various elements in console like:
<p>Lorem...... </p>
or <h3>Lorem.....</h3>
and I want this function to dig only to:
<li class="slider__card slider__margin-t--1" data-slide-id="1"> </li>
element.
My index.html:
<ul class="slider__container">
<!-- 1 slide -->
<li class="slider__card slider__margin-t--1" data-slide-id="1">
<div class="slider__card-pic">
<img >
<img >
</div>
<div class="slider__card-text">
<h3>Excepteur sint occaecat</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Minus debitis laboriosam ea, magni nulla libero.</p>
</div>
</li>
<!-- 2 slide -->
<!-- 3 slide -->
<!-- 4 slide -->
</ul>
PS. I was trying e.stopPropagation() too.
EDIT Solution:
I Found some kind of hack solution, but not ideal... If someone has better idea please let me know:
onSlideClick() {
console.log(this.container)
this.container.addEventListener('click', (e) => {
if (e.target.parentNode.parentNode && e.target.parentNode.parentNode.nodeName == 'LI') {
console.log(e.target.parentNode.parentNode)
}
})
}
Upvotes: 0
Views: 136
Reputation: 21564
Nope, you don't want to stop bubbling, because your code depends on bubbling.
The idea behind your solution is the way to go, but it is not really bullet-proof. You can try to get the parent node until the parent is your ul
.
Using a while loop :
var container = document.querySelector('.slider__container');
container.addEventListener('click', (e) => {
var target = e.target;
if (target === container)
return // no need to check further if click happened on the ul
while (target.parentNode && target.parentNode !== container) {
target = target.parentNode
}
console.log(target.dataset.slideId);
})
ul {
background-color: blue;
}
li {
background-color: pink;
}
<ul class="slider__container">
<!-- 1 slide -->
<li class="slider__card slider__margin-t--1" data-slide-id="1">
<div class="slider__card-pic">
<img>
<img>
</div>
<div class="slider__card-text">
<h3>Excepteur sint occaecat</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Minus debitis laboriosam ea, magni nulla libero.</p>
</div>
</li>
<!-- 2 slide -->
<!-- 3 slide -->
<!-- 4 slide -->
</ul>
Upvotes: 1