So I have a page setup that lets you expend text boxes upon click:
It adds an ‘active’ class to elements upon click and removes it if you click another text box. Now I’d like remove the class if you click on the red background. I’ll also want to add elements to the page shortly so it’s important that this removal only comes from clicking the red portion which is the <body> element.
So here’s what I have on the page now: (note the log will be replaced by the removal of the class)
$('*:not(li)').click(function(){
console.log('foo')
});
The problem is it logs ‘foo’ everywhere you click, even directly on the text boxes which are li elements. How can I make this work only upon click of the background?
Thanks!
Your problem is that you’re bubbling down the HTML stack. By putting the handler on everything, even if you click on an LI, the event will bubble up to its UL. Similarly, $(‘body’) will cause bubbling issues.
You’re best off creating a div outside of your main stack to handle this. Imagine an absolutely positioned div behind most of the page.
If you really want to have everything fire except for LI, your code would need to look more like this: