1

I want to toggle the preventDefault method based on the classname of the link element.

Example:

<a href="#" class="myLink disabled">My link</a>

//TO-DO: enable click only when link doesn't have disabled class
$('.myLink').on('click', function() {
    //DO SOME STUFF
});
Runtime Terror
  • 6,242
  • 11
  • 50
  • 90

3 Answers3

4

You can bind the event on the element which don't have a particular class. Using :not() selector, elements can be excluded.

$('.myLink:not(.disabled)').on('click', function

If the disabled class is applied dynamically, you have to check if the clicked link have that class using hasClass().

$('.myLink').on('click', function(event) {
    if ($(this).hasClass('disabled')) {
        event.preventDefault();

        // return false; // Use when no action should be performed
    } else {
        // Handle event
        ...
    }
});
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • is `return false === event.preventDefault();` ? – Andrew Evt Apr 26 '16 at 05:59
  • @AndrewEvt `return false; === e.preventDefault(); + e.stopPropagation();` – Tushar Apr 26 '16 at 05:59
  • @Tushar, Will `return false;` prevent bubbling of event with `on` event binding ? Just a doubt! – Rayon Apr 26 '16 at 06:03
  • @Tushar the link is more on `return false` there is no mention of *prevent bubbling of event with on event binding* i want to know about this as well :) – guradio Apr 26 '16 at 06:07
  • @Tushar, That was cool! Something new for me:P ...Thanks mate! – Rayon Apr 26 '16 at 06:07
  • @guradio, Some snack for you https://jsfiddle.net/rayon_1990/hqeo0fvy/ ... Also consider the comment under the accepted answer by great _T.J. Crowder_ – Rayon Apr 26 '16 at 06:08
  • 1
    @guradio Quoting from same link _`e.preventDefault()` will prevent the default event from occuring, `e.stopPropagation()` will prevent the event from bubbling up and **`return false` will do both**. Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up._ – Tushar Apr 26 '16 at 06:10
  • 1
    @RayonDabre that was clearer sorry english is not my first language seeing the sample helps understand better :) – guradio Apr 26 '16 at 06:11
1

Try this:

$(".myLink:not(.disabled)").on('click', function() {
    //DO SOME STUFF
});
Alex Art.
  • 8,711
  • 3
  • 29
  • 47
1
<a href="#" class="myLink disabled">My link</a>

//TO-DO: enable click only when link doesn't have disabled class
$('.myLink').on('click', function(e) {
    if ($(this).hasClass('disabled') {
        e.preventDefault();
    }
    // do thomething
});
Andrew Evt
  • 3,613
  • 1
  • 19
  • 35