简体   繁体   中英

How to disable Javascript redirect on click event

I am using a Javascript redirect to redirect visitors after X seconds. However, there is also a link on the page that takes the visitor to the same page. I would like to stop the redirection if the visitors clicks on the link first.

Please note that ,the link is opening in the new window when clicked but the javascript redirect opens in the same window.

This is the code am using in my HTML Page ,

Javascript redirect code:

<script>
<!-- 
timeout = '5000'; // milliseconds/1000th of a sec
window.onload = setTimeout(myRedirect, timeout); // ensure we load the whole page

function myRedirect() {

window.location = "http://www.mypage.com/page1.html";
}
//-->
</script>

and there is this link which opens in new window:

<a href="http://www.mypage.com/page2.php" target="_blank">Click Here</a>

any ideas on how i can achieve this?

store your timeout call in a variable.

var timeout = '5000';
var myTimeout;
window.onload = function(){
    myTimeout = setTimeout(myRedirect, timeout);
}

and when you want it cancelled, clear that timeout in that variable:

clearTimeout(myTimeout)

You just need to clear the timeout when the link is clicked:

<a href="somepage.html" onclick="javascript:clearTimeout(t);">click here</a>

Note that the object 't' must be what is returned from the setTimeout function. So now that will look like:

var t;

window.onload = function() {
    t = setTimeout(myRedirect, timeout);
}

Also, I may point out here that what you are doing here is generally not recommended (there definitely are rules to this exception). It would be better to use HTTP headers for the redirect, but since I don't know what exactly your requirement is, I can't comment.

您应该使用clearTimeout取消setTimeout,请参见此处的示例

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM