I have some clickable divs which contain text. In some cases the text itself is a hyperlink.
I would like to generally be able to click on the div and have it trigger its onclick action, however when clicking directly on a hyperlink, I only want the hyperlink action to trigger and not the div onclick action.
The below sample code illustrates the issue - when clicking the hyperlink, the div turns red (onclick) AND google opens in a new tab. In this scenario I only want google opened in a new tab. When clicking anywhere else on the div the color should change to red.
Thanks in advance,
Dennis
<div id="myDiv" style="height:60px;width:200px;border:solid" onclick="this.style.color='red';"}>
This is NOT a hyperlink.
<br><br>
<a href="https://www.google.com" target="_blank">This IS a hyperlink.</a>
</div>
You can add an event listener, listening on the click
event, and check the target
rather than the currentTarget
.
You just need to check that the target
(the actual element that was clicked) is not an a
tag. In such a case, you would change the color of the currentTarget
(the element the event listener is applied to).
Here is a working snippet:
document.getElementById('myDiv').addEventListener('click', (e) => {
if (!e.target.matches('a')) {
e.currentTarget.classList.add('color');
}
});
div {
height: 60px;
width: 200px;
border: solid;
}
.color {
color: red;
}
<div id="myDiv">
This is NOT a hyperlink.
<br><br>
<a href="https://www.google.com" target="_blank">This IS a hyperlink.</a>
</div>
Note - I've adapted the code to use proper CSS rather than inline styles. This has a lot more mileage in the long run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With