<div>
<div class="child-1">Clickable child</div>
<div class="child-2">Non-clickable child</div>
</div>
Let's say child-1 is clickable, and child-1 is a 3rd library element so I can't change it. Right now the clickable area is only child-1. How can I trigger child-1 click when I click child-2?
CodePudding user response:
Add the onclick listener to the parent of the child-1
and child-2
. That way, the event bubbles up to the parent div
and you can act upon it accordingly.
Using event.target
you can identify where the actual click happened (between child-1
and child-2
)
<div id="wrapper">
<div class="child-1">Clickable child</div>
<div class="child-2">Non-clickable child</div>
</div>
JS:
const wrapper = document.getElementById('wrapper');
wrapper.addEventListener('click', (event) => { ... });
CodePudding user response:
You can add a click event listener to click2 and then get that to trigger a click on click1 element.
const child1 = document.querySelector('.child-1');
const child2 = document.querySelector('.child-2');
child2.addEventListener('click', function() {
alert('child2 clicked');
child1.click();
});
child1.addEventListener('click', function() {
alert('child1 clicked');
});
<div>
<div class="child-1">Clickable child</div>
<div class="child-2">Non-clickable child</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>