Reputation: 124
I'm creating a div which is shown(toggled) by clicking on another element.
It should be shown when i click an anchor(#toggle-contents
) and hidden if i click on the same anchor or somewhere else in the document.
I'm following the code in this how-to: Creative overlay/popup with jQuery.
It is currently working for the first time it's clicked, - but then it gets displayed and hidden shortly afterwards.
The markup:
<div id="block-header">
<a id="trigger-contents">Toggle</a>
</div>
<div id="block-contents">
</div>
The javascript:
function registerToggleDiv( trigger, toggle )
{
$( '#' + trigger ).click(function()
{
$( '#' + toggle ).toggle(function()
{
console.log('toggle');
$(document).click(function(event)
{
if ( !($(event.target).is('#' + toggle ) ||
$(event.target).parents('#' + toggle ).length ||
$(event.target).is( '#' + trigger )))
{
console.log('toggle hide');
$('#' + toggle ).hide(500);
}
});
});
});
}
registerToggleDiv( 'trigger-contents', 'block-contents' );
I tried to find to error comparing to other toggle-questions here but didn't find any hint.
Thank you for any hints!
Upvotes: 3
Views: 804
Reputation: 4705
When you click on trigger
, propagation will happen and document onclick
will fire.
You are binding to document onclick
event :
$('#' + toggle ).hide(500);
you should stop propagation in clicked element to prevent document click as below :
$( '#' + trigger).click(function(e){
e.stopPropagation();
});
Upvotes: 1