Sunday 20 July 2014

Why $(document).ready(function(){});?

Posted by Shiva on 08:56 in , | 3 comments

Remember the traditional method of calling $(document).ready() ?
<script>
$(document).ready(function(){

// Code Goes Hear
});
</script>

We have to use this function in the head section of our html page. This is because we do not have all our elements instantiated when the page is being compiled.

After loading the complete page,  we do not need to write $(document).ready(function(){ }); at all.



Example 1 :

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>add demo</title>
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script>
    // in head section if we want to run jquery we need to write document ready like below ..
    $(document).ready(function(){
    $("button").click(function(){
    alert("click works");
    });
    });
 //for more conformation copy this code and remove document ready and check
  </script>
</head>
<body>
    <button>click me!</button>
</body>
</html>

 Example 2 :
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>add demo</title>
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  </head>
<body>
    <button>click me</button>
 <script>
    // hear the DOM element (button) is ready so no need to write document ready
    $("button").click(function(){
    alert("click works");
    });
  </script>
</body>
</html>


3 comments: