Client-Side Processing

Peter Wood

Client-side processing

JavaScript

Client-side scripting

Document Object Model (DOM)

Document methods and properties

Events

Calling a function

Table of squares function

Comments on previous script

Defining a function

Event handlers

Event handlers example

Event listeners

Functions and form fields

Defining the function myTranslate

Navigating the DOM tree

Finding elements by name

Finding elements by name (function body)

Using CSS selectors

Adding elements

Deleting elements

Using jQuery

Using jQuery to add elements

Finding elements by name (jQuery)

DOM and XML

jQuery method to load an XML file

$.get("rss-fragment.xml", 
      function( xml ) {
        ...
      },
      "xml"
    );

Retrieving RSS item titles

Retrieving JSON data

  • consider the following form:
    Address
  • the code for the form is as follows:
    <form>
      <fieldset>
        <legend>Address</legend>
        <select id='addressCountry'>
          <option value='na'>Please select a country</option>
          <option value='ca'>Canada</option>
          <option value='gb'>United Kingdom</option>
          <option value='us'>United States</option>
        </select>
        <label for='addressState'>County/Province/State:</label>
        <select id='addressState'></select>
      </fieldset>
    </form>
    
  • say we want to populate the drop-down list of counties/provinces/states by retrieving a list for the selected country from the server
  • we also want to overwrite County/Province/State with the term appropriate for the country selected
  • (This example is taken from the book "Web Development with jQuery" by Richard York, Wrox Press, 2015.)

JSON country data

  • there are JSON files for each country: ca.json, gb.json and us.json
  • the one for the UK (gb.json) looks as follows:
    {
        "name" : "United Kingdom",
        "iso2" : "GB",
        "iso3" : "GBR",
        "label" : "County",
        "states" : {
            "0"   : " ",
            "794" : "Angus",
            ...
            "988" : "York"
        }
    }
    
  • label gives the correct term for County/Province/State
  • states will be used to populate the drop-down list

Code for JSON retrieval (1)

  • the code is as follows:
      $('#addressCountry').change(
        function() {
          // Remove all of the options
          $('#addressState').empty();
          if (this.value === 'na') return;
          $.getJSON(
            this.value + '.json',
            function(json) {
              // Change the label
              $('label[for="addressState"]').text(
                json.label + ':'
              );
              ... see next slide
            }
          );
        }
      );
    
  • change (rather than click) event is needed for select in Chrome and Safari
  • jQuery provides a getJSON function which retrieves a JSON file from the server
    • first argument is the name of the file
    • second argument is a function to be called on success and passed the JSON data

Code for JSON retrieval (2)

  • the code for setting the options is as follows:
                // Set the options ...
                $.each(
                  json.states,
                  function(id, state) {
                    $('#addressState').append(
                      $('<option/>')
                        .attr('value', id)
                        .text(state)
                    );
                  }
                );
    
  • each iterates over each key/value pair of the states
  • for each one, the function is called and passed the key and value (id and state)
  • a new option is added each time, with its value attribute set to the id of the state and its text set to the value of state

Exercises

  1. Implement the following functions:
    • Function celsius returns the Celsius equivalent of a Fahrenheit temperature using the calculation C= 5.0/9.0 * (F-32)
    • Function fahrenheit returns the Fahrenheit equivalent of a Celsius temperature using the calculation F = 9.0/5.0 * C + 32
  2. Use the functions from (1) to write a script that enables the user to enter either a Fahrenheit temperature and display the Celsius equivalent or enter a Celsius temperature and display the Fahrenheit equivalent. You can either write two new functions that call your functions from (1) or modify those functions instead. Your HTML document should contain a form with two buttons and two input fields. The one button initiates the conversion from Fahrenheit to Celsius, while the other initiates the conversion from Celsius to Fahrenheit. The input fields hold the two temperatures: one as input, the other as output. For simplicity, call the functions using onClick attributes. (see slide 15 and slide 16.)
  3. Now modify the code in (2) so that it does not use onClick attributes but instead binds events to the buttons. Remember to use window.onload to delay the bindings until after the page has loaded (as in slide 13).
  4. Reproduce the code to output information from the RSS document fragment as on slide 27 and slide 28, but outputting item descriptions rather than titles. For this, you will need to save a copy of the RSS document in your own web space (see the intranet for instructions). Your HTML page will also need to be there and you will need to access it over the web, using titan.dcs.bbk.ac.uk/~..., where ... is your username. Your HTML page will also need to reference the jQuery library, either remotely or by saving a copy in your web space. The version I use is here.

Links to more information

There are many books devoted to Javascript and/or jQuery. DOM is covered in Chapter 7 of [Moller and Schwartzbach] and Chapter 8 of [Jacobs]. See above for books on jQuery.