Having a dynamic selector (linkTrigger) set up to capture clicks on an element, the challenge lies in not knowing what linkTrigger might be or if it will have any children. Previously with jQuery, everything worked seamlessly.
Clicking on the first green rectangle (excluding the numbers part) displays all 3 handlers working as expected. However, clicking on the numbers within the first green rectangle triggers only the jQuery and javascript2 handlers, as anticipated, since clicking on the span in the green box does not meet the condition:
if (e.target.classList.contains(linkTrigger.substring(1))) {
I'm unable to use css pointer-events none on unwanted children because I'm unsure about the nature of linkTrigger and wish to avoid tampering with its contents.
The issue arises with the javascript2 handler being non-dynamic, requiring me to add this handler manually for every new ".a" container added to the DOM later on.
Is there a more effective solution to address these challenges?
var linkTrigger = '.c'
//jquery works fine and reacts in real-time
$('.wrap').on('click', linkTrigger, function(e) {
var parent = $(this).closest('.a'),
id = parent.attr('data-id')
console.log('jquery: ' + id)
})
//javascript functions properly except when clicking on children (number spans inside the green rectangle) even though it is reactive. I cannot apply **css pointer-events none** to prevent click events on certain children due to uncertainty regarding **linkTrigger**, nor do I want to modify its contents.
document.querySelector('.wrap').addEventListener('click', function(e){
if (e.target.classList.contains(linkTrigger.substring(1))) {
var parent = e.target.closest('.a'),
id = parent.getAttribute('data-id')
console.log('js: ' + id)
}
})
//javascript2 works but lacks reactivity, necessitating manual attachment of this function call to each item when additional ".a" containers are added.
document.querySelectorAll(linkTrigger).forEach(function(el){
el.addEventListener('click', function(e){
var parent = e.target.closest('.a'),
id = parent.getAttribute('data-id')
console.log('js2: ' + id)
})
})
.a{
width:300px;
height:300px;
background:red;
margin:1px;
}
.b{
width:200px;
height:200px;
background:blue;
}
.c{
width:100px;
height:100px;
background:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="wrap">
<div class="a" data-id="0">
<div class="b">
<div class="c"><span>657567645</span></div>
</div>
</div>
<div class="a" data-id="1">
<div class="b">
<div class="c"></div>
</div>
</div>
</div>