0

All the elements with .btn class are bound to a jQuery click event on page load. Is there a way to unbind a single element that uses the class .btn. I tried by adding return false in the onclick event to an anchor tag like this

<a href="index.html" class="btn" onclick="return false;" target="_blank">Link</a>

but it doesn't seem to override or prevent it from performing the click event bound by jQuery

EDIT
Thanks for all the answers, but is there an inline solution to this? Something like onclick="event.preventDefault();"

Also follow up question: Just curious, which among onclick and jQuery event listener gets called first?

2
  • while you can change onclick event why you not just delete the href or change to href="#" Commented Dec 15, 2015 at 6:12
  • 1
    @Mohamed-Yousef I need that link in hence the index.html Commented Dec 15, 2015 at 6:22

3 Answers 3

3

Use unbind() method of Jquery.

<a href="index.html" onclick="return false;" target="_blank" id="xyz">Link</a>      

$(document).ready(function(){
     $("#xyz").unbind("click");
});
Sign up to request clarification or add additional context in comments.

1 Comment

a little explanation wouldnt hurt
1

You can use jquery .not to narrow the selection with a specific button where you need to give this button a unique id:

<a href="index.html" class="btn" id="prevent" target="_blank">Link</a>
<a href="index.html" class="btn"  target="_blank">Link</a>

$(".btn").not("#prevent").click(function(){

});

1 Comment

I already did this but I'm looking for an inline solution. This was my last resort. Thanks!
0

If you added event click via delegation like this :

$(document).on('click', '.btn', function(e){});

You must stop event propagation from your own .btn

$('.myOwnBtn').on('click', function(e) {
    e.preventDefault();
});

How do you add event click on your .btn ? If you add event by click, you can off it

$('.myOwnBtn').off('click');

Onclick attribute is executed before click event from jquery and is completely independent from click event from jquery.

2 Comments

Thanks! So does that mean whatever you put in onclick gets overridden by jQuery? Also which does get called first? onclick or the jQuery click event?
Attribute onclick is executed first but it is independent from event handler system.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.