If you want to ensure that all clicks are captured and checked to determine if they are on an anchor from a different domain, here is the code snippet you can use:
document.body.addEventListener("click", function(evt) {
evt.preventDefault();
var anchor = evt.target.closest("a")
if (anchor && anchor.href && anchor.host !== window.location.host) {
document.querySelector(".message").classList.add("active");
window.setTimeout(function () {
window.location.href = anchor.href;
}, 5000);
}
});
.message {
display: none;
}
.message.active {
display: block;
position: absolute;
width: 200px;
height: 100px;
background-color: red;
}
<a href="https://www.example.com">Example</a>
<a href="/">Same Domain</a>
<div class="message">
Whatever you want to say.
</div>
Note: This code does not account for scenarios where users open links in new tabs or windows using keyboard shortcuts. To address this, many organizations opt to include an icon next to external links as a visual indicator.