I have a plain webpage with a singe button.
Using jQuery 3.3.1, a 'click' event is attached to this button such that once this button is clicked, the next click anywhere on the page(document) makes an alert('Clicked!').
<div id="container">
<button id="Btn">Click</button>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#Btn").click(function() {
$(document).click(function() {
alert("Clicked!");
$(document).unbind('click');
});
});
});
</script>
But using this code, the first click on the button itself makes the alert('Clicked!').
I changed the code a bit and attached the 'click' event to $(document) inside a nested $(document).ready() :
<script type="text/javascript">
$(document).ready(function() {
$("#Btn").click(function() {
$(document).ready(function() { // <--here
$(document).click(function() {
alert("Clicked!");
$(document).unbind('click');
});
});
});
});
</script>
This works as intended but I still can't infer such behaviour: why do I need to include a nested $(document).ready() ?
Or is there any other approach to achieve the desired functionality?