jQuery Attaching events and manipulating the DOM inside ready()


Example

Example uses of $(document).ready():

  1. Attaching event handlers
    Attach jQuery event handlers
$(document).ready(function() {
  $("button").click(function() {
    // Code for the click function
  });
});
  1. Run jQuery code after the page structure is created
jQuery(function($) {
// set the value of an element.
   $("#myElement").val("Hello");
});
  1. Manipulate the loaded DOM structure
    For example: hide a div when the page loads for the first time and show it on the click event of a button
$(document).ready(function() {
  $("#toggleDiv").hide();
  $("button").click(function() {
    $("#toggleDiv").show();
  });
});