I'm building a debugging tool for myself. What I want it to do is place a class on any element whenever it's clicked.
Something like this:
$('*').click(function(){$(this).toggleClass('debug')});
That actually worked, except that it toggles "debug" for ALL elements.
For example:
<body>
<div id='3'>
<div id='2'>
<div id='1'></div>
</div>
</div>
</body>
If I clicked on <div id="1">
, it will add a class called "debug" to <div id="2">
and <div id="3">
.
What's happening is when you click on <div id="1>
, it counts as a click to all 3, because technically, all divs were clicked. So I've thought about having an array that holds all the HTML elements.
So far, I have:
window.v = [];
$('*').click(function(){window.v.push(this)});
Following that, it's:
$(window.v[0]).toggleClass('debug');
Unfortunately, when this:
$(window.v[window.v.length]).toggleClass('debug');
...or the above executes, it doesn't do anything. Sometimes, it places the "debug" class on the body tag.
So, I'm not exactly sure if using an Array is the best route for this. Does anyone else have any ideas on how to universally click on any element and place the debug class on it?
Thanks in advance.
I'm building a debugging tool for myself. What I want it to do is place a class on any element whenever it's clicked.
Something like this:
$('*').click(function(){$(this).toggleClass('debug')});
That actually worked, except that it toggles "debug" for ALL elements.
For example:
<body>
<div id='3'>
<div id='2'>
<div id='1'></div>
</div>
</div>
</body>
If I clicked on <div id="1">
, it will add a class called "debug" to <div id="2">
and <div id="3">
.
What's happening is when you click on <div id="1>
, it counts as a click to all 3, because technically, all divs were clicked. So I've thought about having an array that holds all the HTML elements.
So far, I have:
window.v = [];
$('*').click(function(){window.v.push(this)});
Following that, it's:
$(window.v[0]).toggleClass('debug');
Unfortunately, when this:
$(window.v[window.v.length]).toggleClass('debug');
...or the above executes, it doesn't do anything. Sometimes, it places the "debug" class on the body tag.
So, I'm not exactly sure if using an Array is the best route for this. Does anyone else have any ideas on how to universally click on any element and place the debug class on it?
Thanks in advance.
Share Improve this question edited Sep 7, 2011 at 22:59 user1385191 asked Sep 7, 2011 at 22:50 iNkiNk 831 silver badge12 bronze badges2 Answers
Reset to default 8Do this:
$( window ).click(function ( e ) {
$( e.target ).toggleClass( 'debug' );
});
Binding click handlers to all DOM elements is a bad idea. Instead, bind one single click handler to the window
object. You can do this because click events bubble up (the DOM tree). In order to determine which element was clicked, use e.target
.
Simple as that :)
Live demo: http://jsfiddle/Ucpzq/1/
Cancel the bubble:
$('*').click(function(evt) {
$(this).toggleClass('debug');
evt.stopPropagation();
});