Upon Link Click And Settimeout
In JavaScript, I am trying to execute a function 2 seconds after a link is clicked, and wait until the function completes its execution before going to the link destination. /* Jav
Solution 1:
You will need to return false
from your onclick event, to cancel the actual browser handled page load.
And since you want to follow the link (once the function is complete) you will need to do that through javascript. But you are using a timeout so you loose the reference to the clicked element, so we need to pass that too in the method (if you want this logic for multiple links)
html
<aonclick="return createTimedLink(this, myFunction, 2000);"href="http://www.siku-siku.com">Link</a>
javascript
functioncreateTimedLink(element, callback, timeout){
setTimeout( function(){callback(element);}, timeout);
returnfalse;
}
functionmyFunction(element) {
/* Block of code, with no 'return false'. */window.location = element.href;
}
Solution 2:
<aonclick="setTimeout(myFunction, 2000);"href="#">Link</a>
JAVASCRIPT
functionmyFunction(){
////your other code//////window.location="http://www.siku-siku.com";//at the end
}
Solution 3:
Yes, the default behavior for a link is a GET request sent by the browser. Imagine that before you register your handler, browser has registered another handler to initiate a get request (just imaginary). This is the case here. You should return false in your inline handler:
onclick = '(function(){ setTimeout(yourFunction, 2000); return false;})()'
or more simpler:
onclick = 'setTimeout(yourfunction, 2000); return false;'
Update:
Use this (it requires jQuery):
$(function () {
$('a').click(function (e) {
e.preventDefault();
var target = $(this).attr('href');
setTimeout('go("' + target + '")', 2000);
});
});
functiongo(target) {
console.log('2 seconds passed');
document.location = target;
}
Post a Comment for "Upon Link Click And Settimeout"