Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does the .bind() not work outside the .ready() function?

Tags:

jquery

On click of a button I am showing an alert message. Below is the code that I am using.

<script type="text/javascript">
// $(document).ready(function(){
    $("#clickHere").bind("click",function(){
        alert('clicked');
     });
 //});
 </script>

As the .ready() line is commented, when I click on the button the alert message is not thrown, but if I uncomment those lines the the alert is thrown. Shouldn't the alert message be shown in both the cases as I have added binding to the button on 'click' event?

like image 246
Sam Avatar asked Jul 06 '26 16:07

Sam


1 Answers

because at the time the javascript block is parsed, the DOM is not ready, hence the element you reference does not exist yet.

like image 174
Nick Andriopoulos Avatar answered Jul 14 '26 19:07

Nick Andriopoulos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!