Reputation: 55
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>
Upvotes: 4
Views: 835
Reputation: 5237
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.
Upvotes: 2
Reputation: 64
Sounds like you either need a custom event listener for click on anchor elements, using event bubbling, or to enhance the onclick listener for your div to be smart enough to inspect the event target.
Something like
if (event.target === this) {
this.style.color='red';
}
Upvotes: 1