0

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!

James
  • 2,195
  • 1
  • 19
  • 22
Marven
  • 71
  • 6

2 Answers2

0

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');
    }
})
James
  • 2,195
  • 1
  • 19
  • 22
0

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);
Rao Ehsan
  • 778
  • 8
  • 15