I have a form system which is dynamically generated.
The code below is the button which calls the calendar.
<input id="btn1_0" type="button" value="☵" class="rsform-calendar-box btnCal rsform-calendar-button btn btn-default" onclick="RSFormPro.YUICalendar.showHideCalendar('cal1_0Container');">
Here's the div which shows up when the above button is clicked. The button toggles the style display:none
when clicked inside the div:
<div id="cal1_0Container" style="clear: both; position: absolute; z-index: 9987;" class="yui-calcontainer single">
Calendar Here
</div>
I want to hide the calendar when someone clicks outside of the div too.
I tried this JS but it won't work as it sets display:none
to the div. What am I doing wrong?
jQuery(document).click(function(event) {
if ( !jQuery(event.target).hasClass('yui-calcontainer')) {
jQuery(".yui-calcontainer").hide();
}
});
You can't bind a click event to the document. Bind it to the body.
jQuery('body').click(function(event) {
if ( !jQuery(event.target).hasClass('yui-calcontainer')) {
jQuery(".yui-calcontainer").hide();
}
});
or
jQuery(document).on('click', 'body', function(event) {
if ( !jQuery(event.target).hasClass('yui-calcontainer')) {
jQuery(".yui-calcontainer").hide();
}
});
You can use some trick like this , check this code below
$(document).dblclick(function (e)
{
var container = $(".yui-calcontainer");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide(); /// or container.toggle(); to show/hide
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body style="height:100% ; width:100%;";>
<div id="cal1_0Container" style="clear: both; position: absolute; z-index: 9987;" class="yui-calcontainer single">
Calendar Here
</div>
</body>
use container.toggle();
for show/hide
let me know if it this is helpful to you .
This was my HTMl
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).dblclick(function (e)
{
var container = $(".yui-calcontainer");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.toggle();
}
});
</script>
</head>
<body style="height:100% ; width:100%;";>
<div id="cal1_0Container" style="clear: both; position: absolute; z-index: 9987;" class="yui-calcontainer single">
Calendar Here
</div>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With