Tags : JavaScript Intro



Using $(document).ready()

$(document).ready() allows us to wait until all the web elements are loaded before any JavaScript code is loaded. More info here

Watch the video and check out our implementation of $(document).ready()

index.html

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="css/example.css">
    <script src="scripts/jquery-1.11.3.js"></script>
    <script src="scripts/myscript.js"></script>
  </head>
  <body>
    <div class="actions">
      <button id="bark">Bark</button>
      <button id="growl">Growl</button>
      <button id="hide">Hide</button>
      <button id="blue">Background Blue</button>
      <button id="none">Remove Background</button>
    </div>
    <div class="activity-tracker">
      <ul></ul>
    </div>  
  </body>  
</html>

example.css

.turn-blue {
  background-color: blue;
}

myscript.js

$(document).ready(function(){
  $("button#blue").on("click", function(){
    var makeBlue = "Full moon tonight!";
    $(".activity-tracker ul").prepend("<li>"+ makeBlue +"</li>")
    $("body").addClass("turn-blue");
  })

  $("#none").on("click", function(){
    var makeClear = "It is daytime";
    $(".activity-tracker ul").empty().prepend("<li>" + makeClear +"</li>")
    $("body").removeClass("turn-blue");
  })

  $("button#bark").on("click", function(){
    $(".activity-tracker ul").prepend("<li>Woof woof!</li>")
  })

  $("button#growl").on("click", function(){
    $(".activity-tracker ul").prepend("<li>Was that a bear?</li>")
  })

  $("button#hide").on("click", function(){
    $(".activity-tracker ul").prepend("<li>Climb up a tree!</li>")
  })
})

Try the following:

  • Load the scripts inside the head tag and use $(document).redy() to make it work (use any of examples you worked on previously).