3

How would I make sure that this href element is will fire "click" event unless it does NOT have "disablelink" class.

DO NOT PROCESS:

<a class="iconGear download disablelink" href="#">Download</a>

PROCESS:

<a class="iconGear download" href="#">Download</a>

tried this without success:

    $("a.download").not(".disablelink").click(function (e) {
        alert('in');
        e.preventDefault();
    });
0

4 Answers 4

6

This should work:

$("a.download:not('.disablelink')").click(function (e) {
    alert('in');
    e.preventDefault();
});

If the disablelink class is being added dynamically:

$(document).on('click', "a.download:not('.disablelink')", function (e) {
    alert('in');
    e.preventDefault();
});

Check this demo: http://jsfiddle.net/d3rXr/1/

Sign up to request clarification or add additional context in comments.

6 Comments

this will not work if he adds the disablelink class dynamically.
..plus its the exact same statement OP already uses, just slower.
@Rodik - Added a variant that should work even if class is dynamically added.
@jAndy - same: yes to an extend (even though this is a sinlge selector version). But slower? is :not slower than .not()?
@techfoobar: in most cases using inlined-selector statements like :not is slower than their functional variants. Just because it will invoke Sizzle to reduce/filter the resultset whereas the function will just .slice()/.filter() the list. See jsperf.com/sizzle-not-vs-functional-not
|
0
$('a.download').click(function(e){
    e.preventDefault();
    if($(this).hasClass('disablelink')){
        return;
    }else{
      //other stuff;
    }
});

Why don't you check when the anchor is clicked, and if it has the class it returns and does nothing, which would be more readable code I guess.

3 Comments

what's the big deal about if else ?
you are asking to do something if some expression is true... only without the if statement...
What ? I don't know what you mean.
0

You could go like this:

$("a.download").click(function(e) {
    if($(this).hasClass("disablelink")) {
        return false;
    }
    // Normal code
    alert('in');
    e.preventDefault();
});

Comments

0

Firstly, this probably doesn't work because some links had disablelink added to them dynamically, and after they already had the click handler bound to them.

Secondly, you should just check for that class inside the click handler, like so:

$("a.download").click(function (e) {
    if($(this).hasClass('disablelink')){
       e.preventDefault();
       // link is disabled
    }else{
       alert('in');
       // link is active
    } 
});

Comments

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.