I have a link that I have set a preventDefault() method on, because I'm going to have a short animation on the link before it connects to the link address.
My problem is though I'm struggling how to set a preventDefault() to last for 200ms only. I've tried using setTimeout(), but I didn't have any joy?
Basically in the code below I'd like it so that when someone clicks the anchor tag nothing happens for 200ms (I will actually have a fade out animation happen during these 200ms, but doing that is easy enough, it's just the timing on the preventDefault() that I'm struggling with).
CodePen: https://codepen.io/emilychews/pen/BrRZbX
window.addEventListener("load", function(){
var link = document.getElementById("link");
link.addEventListener("click", function(e){
e.preventDefault();
})
});
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100vh;
}
<a target="_blank" href="https://www.google.com" id="link">Google</a>
I can't think of a way to preventDefault
and then resume, but you should be able to navigate manually after a 200ms wait:
window.addEventListener("load", function(){
var link = document.getElementById("link");
link.addEventListener("click", function(e){
e.preventDefault();
setTimeout(() => {
// if you want to open in a new window
window.open(e.target.href);
// if you want to navigate away (same window)
window.location = e.target.href;
}, 200);
})
});