Canna
Canna

Reputation: 3794

javascript click event separation

I want to separate the click event.

All the clicks inside the body tag have to be alerted "outside table",

except the click event inside postit-table class.

This is my code:

html

<table class="postit-table">
    <tbody>
    <tr class="postit-header">
        <td>header</td>
    </tr>
    <tr>
        <td><textarea class="postit-content"></textarea></td>
    </tr>
    </tbody>
</table>

css

.postit-table{
    width: 200px;
    height: 200px;
    background-color: yellow;
}

javascript(jquery):

$("body").bind('click',':not(".postit-table,.postit-table tbody, .postit-table tr, .postit-table tbody tr td")', function (e) {
    alert("clicked outside table!");
});

$(".postit-table").click(function(){
    alert("clicked inside table!");
});

jsfiddle:

http://jsfiddle.net/c5fomgp1/

Unfortunately, if you run the fiddle app, it still calls the outside table click event :(

Can somebody help?

Upvotes: 1

Views: 97

Answers (4)

KooiInc
KooiInc

Reputation: 122888

Looks overcomplicated to me. As already answered by others you can use event.stopPropagation an simplify your code. Something like:

$(document).on('click', clickedoutside);
$('body').on('click', '.postit-table', clicked);

function clicked(e){
    e.stopPropagation();
    alert('clicked inside table!');
};

function clickedoutside(e){
    alert('clicked <b>outside</b> table!');
};

Here's your rewritten jsFiddle

Upvotes: 0

Vivek Malik
Vivek Malik

Reputation: 165

Solved

$("body").bind('click',':not(".postit-table,.postit-table tbody, .postit-table tr, .postit-table tbody tr td")', function (e) {
    alert("clicked outside table!");
});

$(".postit-table").click(function(e){
    e.stopPropagation();
    alert("clicked inside table!");
});

Also Try fro this have other solution . Chears

Upvotes: 3

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123367

Use stopPropagation() on postit-table click event: doing so the click event won't be propagated bubbling up to the body element

Example - http://jsfiddle.net/e5jph1Lt/

$("body").on('click', function() {
    alert("clicked outside table!");
});

$(".postit-table").on('click', function(evt) {
    evt.stopPropagation();
    alert("clicked inside table!");
});

As a sidenote, use on() instead of bind() if you use a recent jQuery version

Upvotes: 3

Parfait
Parfait

Reputation: 1750

Use

e.stopPropagation();

Code

http://jsfiddle.net/9e5128g1/

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Ref.

http://api.jquery.com/event.stoppropagation/

Upvotes: 1

Related Questions