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.
You don’t need to return false for every HTML element, only the ones that bubble to
body, namely all ofbody‘s children.Try adding this:
All clicks have to eventually bubble to
body‘s children (or else you clicked onbodyitself) and this will stop it from propagating further.