Javascript and jQuery

Script Tags


<script>/* JavaScript code here */</script>


<script name="my_script" src="path/or/url/to/my_script.js"></script>
  • When referencing a file, no javascript code should be put inside the tag.
  • The name attribute is optional and is intended for humans only.


    document.write('\x3Cscript src="my_other_script.js">\x3C/script>');

You can dynamically create a script tag and run it.


The HTML script tag is used to identify and run javaScript code.

  • The javascript defined by a script tag is compiled and run immediately after the tag is recognized by the browser.
  • You can use as many script tags in a document as you feel necessary.
  • The browser reads each script tag in the order in which it appears in the document. If a script is defining functions or data that are used by another script, then the defining must be done before use. So the defining scripts must come before the using scripts.
  • type="text/javascript" is required in the script tag in HTML 4 and XHTML, but optional in HTML5.
  • Do not use the <!-- //--> hack with scripts. It was intended to prevent scripts from showing up as text on the first generation browsers Netscape 1 and Mosaic.
  • CDATA is needed for XHTML pages if the script has any HTML characters like < and > in it. <script>//<![CDATA[ ...code... //]]></script>
  • JS security ( Same-origin policy ) prevent scripts hosted at other domains from running unless you setup CORS.

More Resources

Functions and Methods

Call a Function Dynamically

window[varClassName][varFunctionName]( params );
var returned = window[varClassName][varSubClassName][varFunctionName]( params );

Is Defined

// Test if a simple function is defined.
if (typeof myFunctionName === "function")
    console.log( myFunctionName + ' exists!');

// Test if a function within a class/subclass is defined.
if (typeof window[class_name][sub_class_name][method_name] === "function")
    console.log( 'Class function exists!');

Event Listeners and Binding

jQuery On Delegated

 * jQuery 'On' Delegated
 * An event-delegation approach to 'on' attaches an event handler
 * to only one outer element (#my-nav), and the inner element's
 * event ('click' on 'a.item') only bubbles up one level.
 * This also allows you to dynamically add new "a.item" elements
 * to '#my-nav' which will immediately bind.
$( "#my-nav" ).on( "click", "a.item",
    function( e )
        e.preventDefault( e ); // Stops the normal element action.
        console.log( $( this ).text() );

jQuery On

 * jQuery 'On'
 * 'on' can attach to almost any element and listen for almost any event.
$( "a.button" ).on( "click",
    function( e )
        e.preventDefault( e ); // Stops the normal element action.
        console.log( $( this ).text() );

Native JS Event Listener

 * Native Javascript Event Listener.
 * elem: The object you want to listen to.
 * type: The event you want to listen to.
 * functionName: The name of the function to call when the event is fired.
var addEvent = function(elem, type, functionName)
    if (elem == null || typeof(elem) == 'undefined') return;
    if ( elem.addEventListener ) {
        elem.addEventListener( type, functionName, false );
    } else if ( elem.attachEvent ) {
        elem.attachEvent( "on" + type, functionName );
    } else {
        elem["on"+type] = functionName;

// Use examples:

// Bind a function to the 'window' 'load' event.
addEvent( window, "load", someFunctionName );
// Bind a function to the 'window' 'resize' event.
addEvent( window, "resize", someFunctionName );

Inline Binding

 * Attach a function directly to an inline element's event.
<a href="javascript:void(0)" onclick="myJsFunction();">Run JavaScript Code</a>



Alert a message to the browser.

alert('You are being alerted!');


Open a confirmation message in the browser.

if( confirm('Are you sure?') )
    // Continue...

Console Log

Log text or objects to the console.

// Text
console.log( 'loggin text here' );

// Object
console.log( myObj );

// Testing for 'window.console' prevents errors
// in browsers without console.
window.console && console.log('hello');

Time and Timers


// Time-Outs
// Calls a function or executes a code snippet after a specified delay.
setTimeout( function(){
    // Do something here.
}, 5000);

// Or...
function message(){ alert( 'Hi' ); }
setTimeout( message, 1000 );

Timed Intervals

// Timed Intervals
// Calls a function or executes a code snippet repeatedly,
// with a fixed time delay between each call to that function.
// Returns an intervalID.
var intervalTimer = window.setInterval( function(){
    // Do something here.
}, 6000);

// Or...
function message(){ alert( 'Hi' ); }
var intervalTimer = window.setInterval( message, 6000);

// Stop the interval.
clearInterval( intervalTimer );

Convert Seconds to Time

// Convert Seconds to Time
function convertSecondsToTime( secondsIn ){
        var seconds = Math.round( secondsIn );
        var output = '';
        var minutes = 0;
        var hours = 0;
        minutes = Math.floor(seconds/60);
        seconds = seconds-(minutes*60);
        if(seconds.toString().length == 1){
            seconds = "0" + seconds;
        hours = Math.floor(minutes/60);
        minutes = minutes-(hours*60);
        if(minutes.toString().length == 1){
            minutes = "0" + minutes;
        if(hours > 0){
            output += hours + ':';
        output += minutes + ':' + seconds;
        return output;


  • JSON stands for JavaScript Object Notation.
  • JSON is a string not a JavaScript object.
    JSON is a specification for formatting a text string so it can represent structured data. JavaScript objects can be converted to JSON strings and vice-versa but with limitations.
  • functions are not allowed in JSON strings.
    If an object is converted it’s functions are simply omitted from the string.
  • Object keys must be strings enclosed in double quotes ".
  • An object value can be a string, number, JSON object, array, true, false, or null.

People confuse JavaScript object literal syntax with JSON because they look very similar, but if you’re writing JavaScript source code and not defining a string, you’re not dealing with JSON. JSON is a textual, language-independent data-exchange serialization specification for encoding data structures into a string, much like XML, CSV or YAML.

var obj  = {foo: 22};     // Defines a JavaScript object (this is *not* JSON)
var json = '{"foo": 22}'; // Defines a JSON string

You may be working with an object derived from a JSON string, but JSON must first be parsed into a language object before it can be used. Likewise, an object needs to be converted to a JSON string before it can be sent via AJAX or saved to a database or file.


More Resources

Create a string from an object

A JSON string can be created from a JavaScript object using the JSON.stringify method.
See a live demo.

// Define a JavaScript object.
var customer_object = {
    'user_name': 'Bob',
    'user_id': '24735',
    'likes': [{
        '0': 'Walking',
        '1': 'Trees'
    'total_purchases': '6',
    'dislikes': [{
        '0': 'Biking'

// Convert the object into a JSON string.
var customer_json = JSON.stringify(customer_object);

If the object has a function definition, the function is simply omitted when it’s converted to a string.

Create an object from a string

A JavaScript object can be created from a JSON string using the JSON.parse method.
See a live demo.

// Define a JSON string.
var customer_json = '{"user_name":"Bob","user_id":24735,"likes":[{"0":"Walking","1":"Trees"}],"total_purchases":6,"dislikes":[{"0":"Biking"}]}';

// Convert the JSON string into a JavaScript object.
var customer_object = JSON.parse(customer_json);


 * POSTs an ajax request and handles the json response
 * Takes a URL, the post-data, and a callback function and subclass name.
 * An asynchronous request is sent to the URL and the post-data is sent as query parameters.
 * The server returns a json object with at least these keys:
 *     - json.status = `1`: on app success, `error`: on app error
 *     - json.message = {error message}: on error (required.): {some success message}: on success (can be empty).
 * The original request parameters as well as the response data are passed to the callback function.
 * @param string request_url : The URL to send the request to.
 * @param array request_data : Key-value pair data to send with the request.
 * @param string callback_function_name : The callback function name. Optional.
 * @param string callback_class_name : The callback function's class name. Optional.
function send_ajax_request(request_url, request_data, callback_function_name, callback_class_name)
    // Using the jQuery core $.ajax() method.
        url:        request_url,
        data:       request_data,
        type:       'post', // Whether this is a POST or GET request.
        dataType :  'json', // The type of data we expect back from the response (JSON).
        // Code to run if the request succeeds:
        success: function(json_response)
            // If the response is not a json object but the request got a 200: the server created invalid output.
            if (json_response == 0) {
                console.log('Ajax response returned `0`. No JSON data.');
            } else {

                // Check for an error message from the application.
                if (json_response.status == 'error') {
                    console.log('Error: ' + json_response.message);
                } else {

                    // if a callback function is defined...
                    if ((callback_function_name != undefined) && callback_function_name != '') {
                        // If a callback class name was defined...
                        if ((callback_class_name != undefined) && callback_class_name != '') {
                            // Call the callback class function and pass it the JSON response.
                        } else {
                            // If the callback class name was NOT defined...                        
                            // Call just the callback function and pass it the JSON response.
        // If the request fails: raw request and status codes are passed to this function.
        error: function(xhr, status, error)
            console.log('Ajax request failed!');
            console.log('Status: ' + status);
            console.log('Error: ' + error);

// Set some data and call the function.
var data = {};
data['foo'] = 'bar';

// Simple request.

// Request with callback to a global function.

// Request with callback to a class-function.



Cookies have four parameters name, value, expiration, and path.

  • The name is a unique identifier for the cookie. The cookie name must be unique to the path it is set on.
  • A cookie only holds one value and it must be a string.
  • The expiration is the date and time after which the cookie becomes invalid.
  • The path should almost always be set to the root path=/ unless you have reason to set the cookie to a deeper path.
function setCookie(cName, cValue, cExDays)
    var d = new Date();
    d.setTime(d.getTime() + (cExDays*24*60*60*1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cName + "=" + cValue + "; " + expires + "; path=/";

// Set a cookie called "myCookie" with
// a value of "1" which will expire in 90 days.
setCookie( 'myCookie', 1, 90 );


function getCookie( cName ) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + cName + "=");
    if (parts.length == 2)
        return parts.pop().split(";").shift();

// Get the value of a cookie named "myCookie".
var myCookieValue = getCookie( 'myCookie' );


To update a cookie, simply redefine it.


When a cookie expires it is automatically deleted, so to delete a cookie, set it’s expiration date to the past.

function delete_cookie( cookieName )
    document.cookie = cookieName +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
function delete_cookie( name, path, domain ) {
  if( get_cookie( name ) ) {
    document.cookie = name + "=" +
      ((path) ? ";path="+path:"")+
      ((domain)?";domain="+domain:"") +
      ";expires=Thu, 01 Jan 1970 00:00:01 GMT";

Storing More Data

To store more complex data sets in a cookie you must first convert the javascript object into a string. After you retrieve the cookie value, you must then convert it back to a javascript object.

// Set a JS object.
var customerJsonObj = {
    'userName': 'Bob',
    'userId': '24735',
    'Likes': [{
        '0': 'Walking',
        '1': 'Trees'
    'totalPurchases': '6',
    'Dislikes': [{
        '0': 'Biking'

// Convert the jSon object into a string.
var customerJsonString = JSON.stringify(customerJsonObj);
// Set a cookie called 'customer', set the jSon
// string as its value and set a 90-day expiration.
setCookie('customer', customerJsonString, 90);

// Get the raw value of the cookie we just set.
var rawCustomerCookieValue = getCookie('customer');

// Parse the string into a jSon object.
var newCustomerJsonObj = JSON.parse(rawCustomerCookieValue);

Module Pattern

// Standard module pattern enclosure.
var module = (function(){
    /* module code */

// jQuery module pattern enclosure.
var module = (function($){
    /* module code */

See a demo on

// jQuery Module definition.
var module = (function($){

    // Private variable.
    var privateValue = 0;

    // Public functions.
    function getValue()
        return privateValue;

    function setValue( value )
        privateValue = value;

    function incrementValue()
    // Return public functions.
    return {
        getValue: getValue,
        setValue: setValue,
        incrementValue: incrementValue


jQuery( document ).ready(function() {
    // Use the module.
    console.log( module.getValue() );          // Returns: 0
    module.setValue( 5 );                      // Set the value to 5
    console.log( module.getValue() );          // Returns: 5
    module.incrementValue();                   // Increment the number
    console.log( module.getValue() );          // Returns: 6

This pattern is a way of creating a self-contained module or library that can be accessed by other scripts.

When JavaScript executes, the module is immediately bound to a variable. This is done by wrapping the content of the module in a self-executing function which returns the module’s public functions to the variable. The module’s public functions and properties can then be accessed from the variable using the . (dot notation property accessor) like so: module.myFunction();.

Documentation Standards

Getting Started with JSDoc 3