Reputation: 3794
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:
Unfortunately, if you run the fiddle app, it still calls the outside table click event :(
Can somebody help?
Upvotes: 1
Views: 97
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
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
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
Reputation: 1750
Use
e.stopPropagation();
Code
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