I attempted to create a function for displaying and hiding a div. To hide the div, users can use the close button or click outside the div. However, I encountered an issue where the close function to hide the div runs first if the user clicks an element outside the div before the div is shown:
Here is the HTML code:
$('#close-add').on('click', function() {
$("#add-shipping-modal").hide();
});
$('#new-shipping').on('click', function() {
$("#add-shipping-modal").show();
});
$('body').click(function(event) {
setTimeout(
if (!$(event.target).closest('#add-shipping-modal').length && !$(event.target).is('#add-shipping-modal')) {
if ($("#add-shipping-modal").css('display') != 'none') {
$("#add-shipping-modal").hide();
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="new-shipping'">Open Div</button>
<div id="add-shipping-modal" style="display:none">
<button id="close-add">Close Div</button>
<p> Show Me </p>
</div>
When clicking the #new-shipping button, the hidden div does not appear. This could be due to the fact that when the #new-shipping button is clicked, it first shows the div and then triggers the body click function.