Tayyab
Tayyab

Reputation: 184

jQuery: preventDefault() not working on anchor link tag (tried many methods!)

I'm trying to prevent anchor link from sending to another page but it's not actually working, I don't even know whyyy. I used preventDefault before and it works every time but this time I don't know what's going on.

Yes i've seen this question on stackoverflow and tried all methods but it's still not working

HTML Code:

 <h2><a id="donta" href="/services.html">Eco Ideas</a></h2>

jQuery Code:

$('#donta').on('click', function(event) {
            event.preventDefault();
            event.stopPropagation();

            alert(event.target.tagName);    //yes it alerts me 'A'

            if(event.isDefaultPrevented()){

                    alert('Prevented!');    //yes it shows this alert but still send me to that link

                    event.stopImmediatePropagation();
                    event.returnValue = false;
                }else{

                    // NOPE, it doesn't show this "ELSE" part...means the below alert doesn't show up...means according to browser or jQuery it is now PREVENTED

                    alert('Not prevented but trying to prevent now');
                    event.returnValue = false;
                }
            return false;
});

You can see I tried all methods, but still it send me to that damn link! Thanks in advance, because I know you guys will find a way :)

Upvotes: 0

Views: 2075

Answers (2)

rie
rie

Reputation: 296

There are lot of event-listeners on the link. And 2 of them are listening click event. It seems like while one prevent link, other one don't.

enter image description here

I think trouble may be in this function, because it triggers:

function end(e) {
  clearTimeout(resetTimer);
  resetTimer = setTimeout(function() {
    w.tapHandling = false;
    cancel = false;
  }, 1000);

  // make sure no modifiers are present. thx http://www.jacklmoore.com/notes/click-events/
  if ((e.which && e.which > 1) || e.shiftKey || e.altKey || e.metaKey || e.ctrlKey) {
    return;
  }

  e.preventDefault();

  // this part prevents a double callback from touch and mouse on the same tap

  // if a scroll happened between touchstart and touchend
  if (cancel || w.tapHandling && w.tapHandling !== e.type) {
    cancel = false;
    return;
  }

  w.tapHandling = e.type;
  trigger(e);
}

Upvotes: 1

mazipan
mazipan

Reputation: 183

I usually not set href attribute with value and just set href="javascript:void(0)" when I won't that link was redirected and will set action in that link.

Maybe will work for you too.

Upvotes: 0

Related Questions