Code Snippets - JavaScript

{outline||<1> - }

Navigating

The following JavaScript will navigate the browser to a new page.

window.location.href = '...';

Reloading

The following JavaScript will reload the current page

location.reload(); // reload from cache

location.reload(false); // reload from cache

location.reload(true); // reload from server

Displaying the current URL

The following JavaScript will output the URL of the page in which the javascript is running.

document.write(document.URL);

Displaying the Document Timestamp

The following JavaScript code will output when the document was last updated.

document.write(document.lastModified);

Setting Initial Focus

To set the control with the initial focus on a web page, perform the following steps.


document.getElementById("myControlId").focus();

Submitting a Form

document.forms[0].submit();

Applying Alternating Formats to a Table

The following JavaScript code assumes that the formats for classes even and odd are defined somewhere in your CSS code.

function recolorTable() {

    var rows = '#MyTable tbody tr'
    $(rows).removeClass('even').removeClass('odd');
    $(rows + ':visible:even').addClass('even');
    $(rows + ':visible:odd').addClass('odd');
}

AjaxReloadElement Function

function ajaxReloadElement(url, data, targetSelector, httpMethod) {

    if (httpMethod == undefined || httpMethod == null) {
        httpMethod = 'GET';
    }

    $.ajax({
        type: httpMethod,
        url: url,
        async: false,
        datatype: 'json',
        data: data,
        success: function (response) {

            $(targetSelector).html(response);

        } /* success */
    });   /* ajax */
}

Showing the Print Dialog

window.print();

Highlight Flash

The following code will, for one second, highlight in yellow the page elements specified by the selector argument.

function highlightFlash(selector) {

    $(selector).show();

    $(selector).css('background-color', '#FFFF00');

    setTimeout(function () {
        $(selector).css('background-color', '#FFFFFF');
    }, 1000);

}

Timer

Delayed Function Call

setTimeout("myFunction", ms);

Alternate
setTimeout(function(){
    /* do something */
    }, ms);

Recurring Function Call

var x = setInterval("myFunction", ms);
. . .
clearInterval(x);

Alternate
var x = setInterval(function(){
    /* do something */
    }, ms);
. . .
clearInterval(x);