Kamil Sindi
Kamil Sindi

Reputation: 22852

How To Avoid Triggering A Click Event

I have a toggle panel script in jQuery whereby my content expands and collapses when I click the h2 element.

Problem is I have input fields in that h2 element, which come about when I try to edit something using jEditable. I would like to find a way so that when I click on that input field, I don't get a click event.

My guess is somehow to use the :not selector method but I've tried a bunch of iterations to no avail.

CODE

    //toggle panel content
    $(".panelcollapsed h2").click(function(){
        $(this).siblings(".panelcontent").slideToggle(100, 'easeInQuad');
    });

Upvotes: 1

Views: 98

Answers (4)

Nettogrof
Nettogrof

Reputation: 2136

on your input inside the h2 tag, you can add an event.stopPropagation() on his onclick.

$('#inputInsideH2').click(function(event){
   event.stopPropagation();
   $(this).focus();
};

the event.stopPropagation() will stop the propagation of the click event.

Upvotes: 0

Kostas Maragos
Kostas Maragos

Reputation: 569

Not really sure what your DOM looks like, so just shooting in the dark here. Perhaps, using e.stopPropagation() in the input's click function could do the trick?

Upvotes: 1

N Rohler
N Rohler

Reputation: 4615

You need to check event.target:

//toggle panel content
$(".panelcollapsed h2").click(function(e){
    if ($(e.target).is('h2'))
       $(this).siblings(".panelcontent").slideToggle(100, 'easeInQuad');
});

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 238075

You could test to see if the event originated on an input element, and ignore it if it did:

$(".panelcollapsed h2").click(function(e){
    if (e.target.tagName.toLowerCase() === 'input') {
        return;
    }

    $(this).siblings(".panelcontent").slideToggle(100, 'easeInQuad');
});

This checks the tagName of e.target, the element where the event originated, to see if it is the same as input. If so, return exits the event handler.

Upvotes: 1

Related Questions