Department of Engineering

IT Services

Advanced Javascript

On the DHTML - Javascript page there are some examples of using Javascript to change web-pages. On this page there are some examples of using other people's code to enhance existing pages. Then jQuery is briefly introduced. You need Javascript enabled in your browser for this page to work.

Using Javascript to enhance pages

With Javascript you can enhance your webpages without needing to change the text of the webpage much. For example -

  • Tables - To let users sort tables according to whichever column they want, use sort table (see a sort table example). It identifies the type of data in the column and offers appropriate sort options. Just download the code, add <script src="sorttable.js"></script> then change your table tag to <table class="sortable">
  • Text entry - To change a textedit box into a full editor - use ckeditor. Download the code, add <script src="ckeditor.js"></script> then change your textarea code
    <textarea name="editor1" id="editor1" rows="10" cols="80">
    This is my textarea to be replaced with CKEditor.
    </textarea>
    <script>
    CKEDITOR.replace( 'editor1' );
    </script>
    
  • Dates - To let users insert dates via a graphical calendar, use something like CalendarPopup.js. Load the script and use something like var cal1 = new CalendarPopup();

Rather more work is involved to draw graphics, though various packages exist. See for example a Pie chart using Bonsai

jQuery

The code to access features of a page can become rather verbose, and there are differences between browsers that need to be dealt with. Libraries of facilities (called Frameworks) have been written to hide this verbosity. Here jQuery will be used, though many other Frameworks exist. jQuery lets programmers perform the standard DOM-related tasks more easily, and has some extra features too. To use it, download it then add

<script src="jquery.js"></script>

which will be faster than using

<script src="https://code.jquery.com/jquery-latest.min.js"></script>

The typical jQuery usage is to put initialization code and event handling functions in a function called .ready(). This is triggered when the browser has constructed the DOM and sends a load event. A shortcut to doing this is as follows

<script type="text/javascript">
$(function(){
        // jQuery code, event handling callbacks here
});
</script>

For example, this will make each paragraph disappear when clicked on

$(function(){
    $("p").click(function(){
        $(this).hide();
    });
});

See jquery examples, jquery selectors or jquery defaults for simple usage. Here are examples of how to access particular elements, showing how using a Framework like jQuery can save a lot of time -

  • $("#lastname") - (shorter than document.getElementById('lastname')). The element with id="lastname"
  • $("p:first-child") - All <p> elements that are the first child of their parent
  • $(":contains('Hello')") - All elements which contains the text "Hello"
  • $("[href='default.htm']") - All elements with an href attribute value equal to "default.htm"

Events are supported too. As well as the standard events as shown on the DHTML - Javascript page , there's blur which is executed when the form field loses focus. Here's an example of what can be put in the ready function - it will change input field backgrounds to magenta when they lose focus.

$("input").blur(function(){
    $(this).css("background-color", "#ff00ff");
});

Friendlier forms

Javascript with jQuery is useful when checking the validity of values entered on a form before they're sent to the server.

  • Check for empty fields -

    See the check empty fields example, which has some required fields

  • Check email address -

    With a paragraph like this -

    <p id=first class=email>foo@bar@.com</p>
    
    checkField('first') will return false, because the address doesn't match regular expression requested by the class.
    var FIELD_PATTERNS = {
    integer: /^\d+$/,
    number: /^\d+(?:\.\d+)?$/,
    email: /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}$/i
    };
    
    function checkField(field) {
     var value=$("#"+field).text();
     for (var pattern in FIELD_PATTERNS) {
       if (!$("#"+field).hasClass(pattern)) continue;
       if (!FIELD_PATTERNS[pattern].test(value)) return false;
     }
     return true;
    }
    
    Note that there are regular expressions in this example for integers and floating point numbers too. The checks for validity and emptiness are combined in this example
  • Add tooltips
  • autocomplete - see an example
  • Asking for confirmations if people try to follow certain links - try clicking here