JS Overview

JavaScript (JS) is a programming language implemented in browsers. It is an Object Oriented language that can alter the document object represention of an HTML document and provides for client-side user interaction.

Try the following to see JS in action.

  • Click on the Option button on the navigation bar to reveal the options panel. The transition occurs by altering the DOM using JS.
  • Click on the High Contrast button. The click event is captured with JS code which then modifies the document object style values and redisplays the page. The remaining buttons in the options panel are coded in a similar way.

To illustarte the concepts, consider the following example:

  1. The top buttons have a click and the bottom buttons a hover, event. Try it. Here is the code for the Refresh button:
    <button class="refresh large">Refresh</button>
    button.large { width: 100px; height: 80px;  }
    $('.refresh').click(
    	function() {
    		location.reload();
    	}
    );
    1. Note the HTML button element class attribute values refresh and large. The corresponding class selector .large is being used in CSS and similarly .refresh is used in JS. Selectors are independant of CSS and JS and select nodes in the DOM to be used in either CSS or JS.
    2. In displaying HTML, a browser builds a DOM which includes an object for the button. The CSS declarations are then applied to their respective selectors and the page is displayed. In this case, the width and height attributes of the button object's style object is set to 100px.
    3. The browser then does a significant job of “listening” for events. When the event occurs, control is passed to any JS that catches the event. In this example, the event is a click and is caught in the JS code by the class selctor .refresh.
    4. The click event can receive a paramter such as the result of a function. The desired task is coded in this function, in this case the reload method of the location object is executed to refresh the page.
    5. Significantly, the click event is controlled by the user triggering the event. This event mechanism is used to implement simple user interaction, such as a page reload to complex interaction in online games.
    6. JS has a very cryptic syntax but you will soon become familiar with the typical pattern, selctor, $('.refresh') followed by event, click() followed by function().
    7. The parenthesis, (), is the syntax for passing parametrs to functions or object methods; in this example they include, function(), $(), click(), and reload(). You can think of object methods and functions as the the code that do particular tasks. Can you see what parameters are passed to each object method?
    8. The Object Oriented dot notation is used for executing object methods; .click() and .reload().
    9. JS statements end with a ; and statements are grouped together in { … }.
    10. If this is your first programming experiance, the code can look very cryptic at first and there are quiet a few complex concepts. You will soon become familiar with the syntax as we progress through a few examples. The aim here is to reuse code and gain an overview to help with effective use of a framework.
  2. Here is the code for the High contrast button example:
    <button class="high_contrast large">High Contrast</button>
    button.large { width: 100px; height: 100px;  }
    .high_contrast { background-color: black; color: yellow; }
    $('.high_contrast').click(
    	function() {
    		setStyle($("body"), '; background-color: black; color: #ffff00;');
    	}
    );

    The comments on the syntax in the previous example applies here; the code is almost identical and the pattern is repeated, namely:

    1. selector, identifying brnaches in the HTML DOM; e.g. high_contrast,
    2. event that is triggered by the user interaction; e.g. click (clicking the element of class type high_contrast), and
    3. function that is the code to be executed once the click event has occured. Note the function calls a method, setStyle() which as the name suggests, sets the style object attribute to particular values.
      1. to execute the task, the setStyle() method receives two parameters, seperated by a comma, namely, $("body") and '; background-color: black; color: #ffff00;'. Note the first parameter is itself a function that receives a parameter body. Hence, finally, the body element's style is set to the specified CSS declaration passed in the second parameter, for background colour and colour.
  3. The code for the play buttons with a hover event.
    <button class="not_playing large">Not playing!</button>
    <button class="playing large">Catch Me!</button>
    $('.not_playing').hover(
       function() {
          $('.not_playing').animate( { 'margin-left' : '-=350px' }, 1);
       });
    
    $('.play').hover(
       function() {
          $('.play').animate( { 'margin-left' : '+=70px', 'margin-top' : '+=70px' }, 10);
    });
    

    The comments on the syntax in the previous example applies here; the code is almost identical and the pattern is repeated, namely:

    1. selector, identifying brnaches in the HTML DOM; e.g. not_playing and playing,
    2. event that is triggered by the user interaction; e.g. hover (hovering the mouse over the element), and
    3. function that is the code to be executed once the hover event has occured.
      1. to execute the task, the animate() method receives two parameters, seperated by a comma, for example, a hash of, variable : value pairs { 'margin-left' : '+=70px', 'margin-top' : '+=70px' } and an integer value for the duration of the animation.

HTML5 data-* attribute

A limitation in triggering an event that is responded to with JS is the event does not pass any data. For example, it may be desirable to set the duration of play in an HTML audio element; HTML5 addresses this with code such as, data-duration="30secs". A variable, duration, is created and can be read in JS and set for the audio player. It is also used extensively in CSS frameworks for JS components such as navbars.

According to the W3C specification:

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

In other words, the data is not intended to be displayed to the user but to be used as custom data such as our example for duration of an audio play.

Try visiting this link to see the data- attribute in action.

Here is the code:

<a class="moderated_links" data-site="MDN" data-rating="excellent" href="https://developer.mozilla.org" >
$('.moderated_links').click(function() {
	var site = $('.moderated_links').data('site');
	var rating = $('.moderated_links').data('rating');
	if (rating == "excellent") {
		alert(site + ' is rated ' + rating);
	} else {
		alert(site + ' is not moderated.  You would be much better off here: https://developer.mozilla.org/en-US/');
	}
});

The comments on the syntax in the previous example applies here and the pattern is repeated, namely:

  1. selector, identifying brnaches in the HTML DOM; e.g. moderated_links,
  2. event that is triggered by the user interaction; e.g. click, and
  3. function that is the code to be executed once the click event has occured.
    1. the HTML5 data variables are accessed using the .data method and stored in local variables. In this example the rating variable is tested and a message is displayed accordingly.

Using JS

Keeping content (HTML), presentation (CSS), and events (JS) seperate is essential for modern web development.

Following this advice you would create seperate files for HTML, CSS and JS and use a script element in the HTML file to allow access to the JS code. For perforamnce reasons, the script element is inserted just before the /body end tag. For example:

 …
   <!-- JS includes -->
   <script src="jquery-2.0.2.min.js"></script>
   <script src="custom.js"></script>

</body>

JS implementation varies amongst browser (guess who is the guilty party not following standards? IE). Part of the soulution is to use a JS library such as jQuery. There are also CSS frameworks that provide scripts for cross-browser compatibility.