Reputation: 199
I want to hide any element that is clicked. For example, if <p></p>
is clicked it should hide, or if <div></div>
is clicked it should hide. I tried using:
$(document).ready(function(){
$("*").click(function(){
$(this).hide();
});
});
However, this hides all the elements if one element is clicked.
How can I achieve what I described?
Upvotes: 3
Views: 55
Reputation: 337560
The event will bubble up the DOM until it reaches the document
, and then everything is hidden. You can stop that bubbling by using stopPropagation
on the event:
$("*").click(function(e) {
e.stopPropagation();
$(this).hide();
});
Also note that it's not a good idea to add an event handler to every element in the DOM as there could be thousands. Instead, bind a single handler to the document
using event delegation:
$(document).on('click', '*', function(e) {
e.stopPropagation();
$(this).hide();
});
Upvotes: 7
Reputation: 21759
As an alternate way of e.stopPropagation();
, You could also hide only the targeted element:
$("*").click(function(e) {
$(e.target).hide();
});
Upvotes: 3