Reputation: 11215
This script allows you to click an element all you want, but when you click anything but that element, it fades something out. In my code below I can click all I want inside of $('.wrapper')
and nothing happens, but when I click anything outside of that element, I have $('.popup')
fadeOut.
(function hideElementOnOffClick(elementWrapper, elementToHide) {
$(document).bind('click', function(evnt) {
var $target = $(evnt.target);
if ($target.is(elementWrapper) || elementWrapper.has(evnt.target).length) {
return;
}
elementToHide.fadeOut();
});
})();
then I call the function with the two element classes in it:
hideElementOnOffClick($('.wrapper'), $('.popup'))
It works find if I use $('.wrapper')
instead of elementWrapper and $('.popup')
instead of elementToHide, but when I make it into something I can call on in different places with different classes, it doesn't.
How do I fix the parameters so that this works?
Upvotes: 0
Views: 111
Reputation: 160903
You could use .stopPropagation()
to stop event propagation, this make your code more clear.
function hideElementOnOffClick(elementWrapper, elementToHide) {
elementWrapper.click(function(e) {
e.stopPropagation();
});
$(document).click(function(e) {
elementToHide.fadeOut();
});
}
Upvotes: 3