I have this problem, I want to conditionally stop the anchor from jump.
condition jump
I tried to add some codes in my coditionFun function to conditionally stop it from jumping.
function conditionFun() {
var flag=false;
if(flag){
console.log('you allowed anchor jump'); return true;
} else {
console.log('you stopped the anchor jump');return false;
}
}
I was hoping to get "you stopped the anchor jump" and DO NOT jump to " http://www.google.com.hk ", but it logged "you stopped the anchor jump" and immediately jump to " http://www.google.com.hk ", anyone help me with this? thank you!
Using jQuery would be your best bet. Then you can run your logic whenever the click event happens on the anchor:
<a id="anchor" href="url">Your link<a/>
$('#anchor').click(function(e){
var flag=false;
if(flag){
console.log('you allowed anchor jump');
} else {
//stops the default anchor action from running
e.preventDefault();
console.log('you stopped the anchor jump');
}
})
you can define your own cancel default function.
<a id="alink" href="www.google.com">Google</a>
function cancelDefaultAction(e) {
var evt = e ? e:window.event;
if (evt.preventDefault) evt.preventDefault();
evt.returnValue = false;
return false;
}
function conditionFun(e) {
var flag=false;
if(flag){
console.log('you allowed anchor jump');
return cancelDefaultAction(e);
} else {
console.log('you stopped the anchor jump');
return cancelDefaultAction(e);
}
}
document.getElementById("alink").addEventListener("click", conditionFun);
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.