简体   繁体   中英

How to increase clickable area to include sibling elements?

<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?

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) => { ... });

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>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM