Vanilla Js: Delay Click Event To Add Animation
No jQuery please! I would love not to use jQuery for this, because it's a big library and I only need to do this single thing: I would like to add a short delay to a click event so
Solution 1:
You may try something like this:
document.getElementsByTagName('a').onclick = function (event) {
event.preventDefault();
document.getElementByClassName('animateOut').className += ' out';
setTimeout(function() {
location.href = this.href;
}, 1000);
};
Solution 2:
I can't really take credit for this, the 2 users below (guest271314 and The Alpha) deserve a lot of recognition for what they helped me to achieve. The full code, with a couple of refinements, is:
window.onload = function(){
var links = document.getElementsByTagName('a');
for( var i=0,il = links.length; i< il; i ++ ){
links[i].onclick = clickHandler;
}
functionclickHandler(event) {
event.preventDefault();
var travelTo = this.getAttribute("href");
// add `s` to `Element`var animOut = document.getElementsByClassName("animateOut");
// iterate `animOut` elementsfor (var i = 0; i < animOut.length; i++) {
// add `out` `className` to `animOut` element at index `i`
animOut[i].classList.add("out");
};
// Delay page out until the animation finishessetTimeout(function() {
window.location.href = travelTo;
}, 1000);
};
};
Solution 3:
There should be an "s"
at document.getElementsByClassName
. To add className
to all animateOut
elements can use a for
loop; change this.href
to window.location.href = e.target.href
if expected result is to navigate to href
of clicked a
element; else leave as this.href
is requirement is to refresh current window.location.href
: this.href
within setTimeout
document.getElementsByTagName("a").onclick = function (e) {
// Delay setting the location for one secondsetTimeout(function() {window.location.href = this.href}, 90000);
// add `s` to `Element`var animOut = document.getElementsByClassName("animateOut");
// iterate `animOut` elementsfor (var i = 0; i < animOut.length; i++) {
// add `out` `className` to `animOut` element at index `i`
animOut[i].classList.add("out");
};
Post a Comment for "Vanilla Js: Delay Click Event To Add Animation"