Recently in my work we faced an issue due to some JavaScript conflict on a page where we have modal popups that were not closing when user clicks outside of it and anywhere on page. Normally it does automatically in jQuery pop up. So here we have to add custom code to handle this situation. In this blog I am going to explain how to do it.
In above picture I explained how to do it. So basic trick is to track click event on entire web page and to check it it's X and Y coordinates are inside the BOX of modal window. If yes then do not close it. But if it's out side of it, close the modal popup. Here is the code for the same.
var rect = $('.modalSelector')[0].getBoundingClientRect();
clientX1 = rect.x
clientX2 = rect.x + rect.width;
clientY1 = rect.y
clientY2 = rect.y + rect.height;
In above picture I explained how to do it. So basic trick is to track click event on entire web page and to check it it's X and Y coordinates are inside the BOX of modal window. If yes then do not close it. But if it's out side of it, close the modal popup. Here is the code for the same.
var rect = $('.modalSelector')[0].getBoundingClientRect();
clientX1 = rect.x
clientX2 = rect.x + rect.width;
clientY1 = rect.y
clientY2 = rect.y + rect.height;
if((e.clientX >= clientX1 && e.clientX <= clientX2) && (e.clientY >= clientY1 && e.clientY <= clientY2)){
return;
}
if($('#modalSelector').hasClass('active')){
$('#modalSelector').removeClass('active');
$('. modalSelector').hide();
}
That's it and it will close if you click anywhere on web page outside of modal popup.
No comments:
Post a Comment