Web Programming/JavaScript

Resources:

JavaScript is a scripting language. When attached to a webpage (HTML) it is interpreted by a web browser and can be used to manipulate the webpage by responding to various events. Traditionally JavaScript runs on the client site to create dynamic behaviors, such as form validation, to make a page more interactive. Recently JavaScript is increasingly being used to make asynchronous web requests (ajax) and handle web requests on the server (node.js).

Life CycleEdit

Hello world A JavaScript program is a plaintext file with JavaScript code. When the script file (code) is loaded a JavaScript interpreter parses statements in the file sequentially and carry out the operations. If a statement defines a function the interpreter remembers the definition and only executes the function when it is called. The following JavaScript code defines one function, which uses the alert() function to say "Hello". When the script is loaded it executes one statement, which invokes the sayHello() function, and then it executes what is in the function definition.

function sayHello(){
    alert("Hello!");
}

sayHello();

A client-side JavaScript file is always attached to an HTML file, which allows the script access to the object (DOM) that represents the page. Often times the first thing we do in the script is to attached functions to the page elements to handle various events. The following HTML code defines a button and includes a demo.js to make the page interactive by handling events.

<!DOCTYPE html>
<html>
<head>
  <script src="demo.js" type="text/javascript"></script>
</head>
<body>
<button id="say_hello">Say Hello</button>
</body>
</html>

The demo.js file has the following content.

window.onload = function(){
  document.getElementById("say_hello").onclick = sayHello;
};

function sayHello(){
  alert("Hello!");
}

In the script the implicit window object is used to attached a event handler to the onload event, which takes place when whole web page finishes loading. The event handler is defined as an anonymous function, which is fine because the function is only referenced once. In the function we use the implicit document object (representing the page) to find the button object by its ID and attached the sayHello() function to handle the button's click event. Note that the first three lines of code is a single statement, which is why it needs to be terminated with ";". The anonymous function is not executed till the whole page is loaded and the sayHello() function is not executed till the button is clicked. We have to wait for the page to finish loading before we can attached event handlers to page elements because the elements have to exist before we can reference them.

The script can be included in the HTML directly as follows. This is OK, but it doesn't cleanly separate the content (HTML) and the behavior (JavaScript) and hinders code reuse (you can not use the script on other pages). I will use this style in future examples because the code stay in one file in compact form.

<!DOCTYPE html>
<html>
<body>
<button id="say_hello">Say Hello</button>
<script>
  window.onload = function(){
    document.getElementById("say_hello").onclick = sayHello;
  }

  function sayHello(){
    alert("Hello!");
  }
</script>
</body>
</html>

DOMEdit

The "document" in the previous example points to a DOM (Document Object Model) object that represents the webpage. In fact, before a browser draws a page on the screen it has to download the HTML code that defines the page, and then constructs a DOM object in memory for the page. So the DOM object for a page is the underlying data structure for rendered page on the screen. We can modify the page on screen by changing its DOM object, for example modifying the content or the style of an element, adding a new element, and removing an element.

In the next example we say hello by changing the content of a paragraph instead of using a popup window, which can be disturbing. The paragraph element has property called innerHTML representing its content. We can change this property to change the content of the paragraph on the web page.

<!DOCTYPE html>
<html>
<body>
<button id="say_hello">Say Hello</button>
<p id="output"></p>

<script>
  window.onload = function(){
    document.getElementById("say_hello").onclick = sayHello;
  };

  function sayHello(){
    var output = document.getElementById("output");
    output.innerHTML = "Hello";
  }
</script>
</body>
</html>

EventsEdit

In addition to the onclick event there are many other events we can choose to handle. Most of the events are triggered by user actions. Sometimes we want to programmatically trigger a event with a delay or periodically. The following example uses a timer to delay the calling of a function. The setTimout() function takes two parameters: the first one is the name of function we want to call when the timer expires and the second parameter specifies the delay in milliseconds.

<!DOCTYPE html>
<html>
<body>

<p id="display">5</p>

<button id="start">Start</button>

<script>
  document.getElementById("start").onclick = 
    function() {
      var seconds = document.getElementById('display').innerHTML;
      setTimeout(timesUp, seconds*1000);
    };
  
  function timesUp(){
    alert('Time is up!');
  }
</script>
</body>
</html>

It would be more interesting to animate the count down on the page, which means we need to update the content of the paragraph periodically. We can set the timer with an interval and clear it when the count reaches zero. This idea is demonstrated in the next example.

<!DOCTYPE html>
<html>
<body>

<p id="display"></p>

<button id="start">Start</button>

<script>
  var seconds = 10;
  var timer;

  document.getElementById('display').innerHTML=seconds;
  document.getElementById("start").onclick = 
    function() {
      timer = setInterval(update, 1000); // expires every second
    };
  
  function timesUp(){
    alert('Time is up!');
  }
  
  function update(){
    seconds = seconds - 1;
    document.getElementById('display').innerHTML=seconds;
    if (seconds==0){
      clearInterval(timer);
      timesUp();
    }
  }
</script>
</body>
</html>

We can build a complete stop watch using this idea.

<html>
<head>
  <script src="stopwatch.js" type="text/javascript"></script>
</head>
	
<body>
<span id="mm">00</span>:<span id="ss">00</span>
<br/>
<button id="reset">reset</button>
<button id="start">start</button>

<script>
window.onload = function(){
  document.getElementById("reset").onclick = reset;
  document.getElementById("start").onclick = start;
};

var timer = null;
var minutes = 0;
var seconds = 0;
 
function reset(){
  //alert("reset");
  document.getElementById("ss").innerHTML = "00";
  document.getElementById("mm").innerHTML = "00";
  minutes = 0;
  seconds = 0;
}

function start(){
  timer = setInterval(update, 100);
  document.getElementById("reset").disabled = "disabled";
  document.getElementById("start").innerHTML = "stop";
  document.getElementById("start").onclick = stop;
}

function stop(){
  clearInterval(timer);
  document.getElementById("reset").disabled = "";
  document.getElementById("start").innerHTML = "start";
  document.getElementById("start").onclick = start;
  //alert("stop");
}

function update(){
  seconds++;
  if (seconds > 59){
    seconds = 0;
    minutes++;
  }
  if (seconds < 10){
    document.getElementById("ss").innerHTML = "0"+seconds;
  }else{
    document.getElementById("ss").innerHTML = seconds;
  }
	
  if (minutes < 10){
    document.getElementById("mm").innerHTML = "0"+minutes;
  }else{
    document.getElementById("mm").innerHTML = minutes;
  }
}
</script>
</body>
</html>

jQueryEdit

jQuery is a JavaScript library that extends the features of "native" JavaScript. It is the most popular JavaScript library because it

  • simplifies DOM manipulation,
  • allows element selection via CSS selector,
  • addresses browser incompatibility issues,
  • offers functional programming abilities (map an operation to a set of elements),
  • offers method chaining by returning the caller object from most functions.

SyntaxEdit

Simple syntax rules can be found at

Common utility methods include

Some interesting constructs include:

$(function () {
  //code here
});

is a shorthand expression for

$(document).ready(function(){
  //code here
});

Any code that depends on a fully loaded page needs to go into this function.

The following is called a immediate function that run immediately without waiting for the document to become ready: a function is defined and called upon in a single statement.

  (function($){
    //code here
   })(jQuery);

Element SelectionEdit

jQuery provides a much richer API for selecting HTML elements in almost all possible ways you can imagine. Most selectors are described at http://www.w3schools.com/jquery/jquery_selectors.asp and you can find a comprehensive demo at http://www.w3schools.com/jquery/trysel.asp

A jQuery selector finds/selects a number of HTML elements, on which we can apply operations.

DOM ManipulationEdit

jQuery makes DOM manipulation easier by providing a rich set of methods we can use. The following are the main categories of such methods:

The following example generates a new square (div) and added to a parent container when the button is clicked.

<!DOCTYPE html>
<html>
<head>
<style>
#box{
  height: 200px;
  width: 200px;
  border: 1px solid black;
}

.square{
  height: 20px;
  width: 20px;
  background-color: blue;
  float: left;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $('button').click(function(){
    var square = $('<div>').addClass('square');
    $('#box').append(square);
  });
});
</script>
</head>
<body>
<div id="box"></div>
<button id="button">add square</button>
</body>
</html>

CSS ManipulationEdit

The ideal way to manipulate style information is to define CSS classes and change the styles of elements by adding them to a class or remove them from a class: get and set CSS classes.

jQuery also provides a general-purpose .css() function for manipulating individual CSS properties directly: css() method. When the css() method is called with one parameter, it gets a property with the same name as the parameter. When it is called with two parameters, it sets the property with the value as the second parameter. When the css() method is called on a set of selected elements it behaves differently depending on whether it is a get or a set: get returns the property value of the FIRST selected/matched element and set changes the property values of ALL selected elements.

Event HandlingEdit

jQuery is designed to respond to all kinds of events on an HTML page.

EffectsEdit

The following effects can be achieved using jQuery:

jQuery UIEdit

jQuery UI is a collection of GUI widgets built with jQuery, HTML, and CSS. A getting started guide can be found on jQuery learning center.