Reputation: 14529
I'm making a small site where if you click on the background, you get a colorpicker allowing you to change the background color.
The problem is that this colorpicker is now showing up no matter where I click, because of event bubbling. I doubt the solution here is adding "return false" to every single HTML element on the entire page. What can I do about this?
The Javascript:
var colorPicker = $.farbtastic('#colorpicker');
var bodyBackgroundColor = $('body').css('background-color').rgbToHex();
$('body').click(function() {
//Set the link to the field displaying the chosen color.
colorPicker.linkTo('#newcolor');
//Set the color on the colorpicker wheel.
colorPicker.setColor(bodyBackgroundColor);
//Set oldcolor field values
$('#oldcolor').val(bodyBackgroundColor);
$('#oldcolor').css('background-color', bodyBackgroundColor);
//Set newcolor field values
$('#newcolor').val(bodyBackgroundColor);
new Boxy($('#form_changecolor'));
return false;
});
Here's an overview of what the HTML looks like:
<html>
<body>
<div id="wrapper">
<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>
</div>
</body>
<html>
The page layout is such that the Header and footer background and same color and content is a different one.
Clicking on header or footer and changing that color changes both, because that color is actually the body-background. Content changes only content.
The problem with the delegate solution is that now is just doesn't work anymore at all. And the stoppropagation method basically does the same thing.
I need some propagation turned on, but not all of it.
Upvotes: 2
Views: 633
Reputation: 2173
You don't need to return false for every HTML element, only the ones that bubble to body
, namely all of body
's children.
Try adding this:
$(function(){
$("body").children().click(function(e){
e.stopPropagation()
});
});
All clicks have to eventually bubble to body
's children (or else you clicked on body
itself) and this will stop it from propagating further.
Upvotes: 3
Reputation: 413709
Instead of handling the bubbling yourself, let jQuery do it:
$('body').delegate('body', 'click', function() {
// your code
});
The jQuery code will verify that the event target matches the selector ("body") before continuing on with your code.
Upvotes: 3