Tags : JavaScript Intro



Manipulation in Jquery

We will now learn how to manipulate web elements. We will start by adding and removing classes to elements. Then we will try to add list item (li) to empty unordered list (ul).

index.html
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="css/example.css">
  </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>  
    <script src="scripts/jquery-1.11.3.js"></script>
    <script src="scripts/myscript.js"></script>
  </body>  
</html>
myscript.js
$("button#blue").on("click", function(){
  $(".activity-tracker ul").prepend("<li>Full moon tonight!</li>")
  $("body").addClass("turn-blue");
})

$("#none").on("click", function(){
  $(".activity-tracker ul").empty().prepend("<li>It is daytime!</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>")
})
example.css
.turn-blue {
  background-color: blue;
}

Try the following:

  • Create a simple web page that changes the background from red, blue and yellow. Also, add a button remove the background.
  • Add a button to the web page "Ring bell" and that adds "Ding dong" to the screen (use and ul and an li to do this. Also, the append or prepend method).
  • Add more actions with buttons to the page, be creative.