user1952949
user1952949

Reputation: 57

prevent click event from element but not from <a> children

my code looks like this:

<div class="disabledClickevent">
  <ul>
    <li><a>link1</a></li>
    <li><a>link2</a></li>
  </ul>
</div>

the div has a click event that gets disabled with return false; my problem is that this also disables the <a> links

Upvotes: 0

Views: 159

Answers (5)

Matt Browne
Matt Browne

Reputation: 12429

If you don't plan to add new "disabledClickevent" divs to the page via Javascript, you could just do this:

$('.disabledClickevent').click(function() {...});

or

$('.disabledClickevent').bind('click', function() {...});

That attaches the event only to the already-existing div, without doing any sort of delegation, so the links will just work normally as you want them to.

To be clear, this is only a viable solution if all of the "disabledClickevent" divs that you plan to have already exist on the page at the time that you bind the event.

Upvotes: 0

PSR
PSR

Reputation: 40358

 $(document).on('click','.disabledClickevent' function(e) {
   if( e.target !== this ) 
   //clicked out side
 return;    
    //clicked inside
});

Upvotes: 2

A. Wolff
A. Wolff

Reputation: 74410

Could be a solution:

$('.disabledClickevent').on('click',function(e){
     if($(e.target).is(':not(a)'))
        return false;
});

Or set click handler to links:

$('.disabledClickevent a').click(function(e){
    e.stopPropagation();
});

Upvotes: 2

tymeJV
tymeJV

Reputation: 104795

I would do this:

$(".disabledClickevent").on("click", ":not(a)", function(e) {
    //do stuff with your div
});

This excludes a from the click event.

Upvotes: 2

Julian Pongasi
Julian Pongasi

Reputation: 11

you can use the :not() selector in jQuery

check this link out http://api.jquery.com/not-selector/

hope this helps.

Upvotes: 0

Related Questions