jQuery Usage Notes

Some jQuery usage notes for useful/common stuff:

To run script when the browser reaches ready state:

$(document).ready(function(){
    //do stuff here
});

Detecting browser type, eg:

if ($.browser.webkit){
     alert( "this is webkit!" );
}

Valid values are webkit, opera, msie, mozila

See here.

Change attribute value of an element:

$('#elementId').attr('attributename', 'new attribute value');

More, see here.

Coding around lack of trim() in IE’s Javascript support

IE8 doesn’t support trim() on Strings (Firefox and other browsers do). To workaround this, you can perform the same operation using some regex on a String:

example.replace(/^s+|s+$/g, '')

… this matches one or more spaces anchored at the start of the line, or one or more spaces anchored at the end of the line, replaces with ”, and then globally replaces to do both.

Extracting cookies using Javascript

Cookies in the current page can be extract using Javascript using ‘document.cookies’ which returns a ‘;’ separated String of all the current cookie values.

You can parse the values with some script like this:

function getCookie(name) {
    var result = '';
    var cookies = document.cookie.split(';');
    for ( var i = 0; i < cookies.length; i++) {
        //alert(cookies[i]);
        var cookie = cookies[i].split('=');
        if (cookie[0].replace(/^s+|s+$/g, '') == name)
            result = cookie[1];
    }
    return result;
}