JavaScript and jQuery

If you are new to JavaScript or use it everyday it’s worth re-reading this article every once in a while for a refresher: A re-introduction to JavaScript from the Mozilla Developer Network.

Data Types

Primitives

Primitives are not objects and have no methods or properties. There are 6 primitive data types:

Objects

Convert json to Array

/**
 * Converts a json object to an array object.
 */
function get_array( data_obj )
{
    var array_obj = [];

    for( var key in data_obj ){
        if ( data_obj.hasOwnProperty(key) ){
            array_obj.push( { name:key, value:data_obj[key] } );
        }
    }

    return array_obj;
}

Tests

DOM Element

// Test if a DOM element exists.
if ($('selector').length)
{
    console.log('element exists!');
}

Email Address

// Test for a valid email address.
// http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
var emailaddy = 'a@b.com';
if (emailaddy.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/))
{
    console.log('email is valid!');
}

Attaching a function to an event like so: window.onload = myFunc; works, and many people do it, however, only the last function attached to an event will get executed. This means that if there is another function further down the code which also attaches to the same event, only the last function attached will actually fire with the event. To prevent this conflict it is best to attach a listener, not a function, to an event.

This native JavaScript function can be used to add event listeners to elements.
It tests if the element exists and which function (addEventListener or attachEvent) to use with it, much like what happens behind the scenes in jQuery for stuff like jQuery(window).resize();.

DOM Elements

Create


// Create a script link tag in the head.
// Create the tag.
var new_script_link = document.createElement('script');
// Add attributes to the tag.
new_script_link.src = 'url-to-my-new-script-file.js';
new_script_link.type = 'text/javascript';
new_script_link.id = 'new-script-link-id';
// Attach the created tag along with it's attributes to the DOM.
document.getElementsByTagName('head')[0].appendChild( new_script_link );

// Creates a form element to post data dynamically.
function postData(path, params)
{
    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", path);
    form.setAttribute("target", "_blank"); // This opens the form in a new tab.
    
    for(var key in params)
    {
        if(params.hasOwnProperty(key))
        {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);
            form.appendChild(hiddenField);
        }
    }
    
    document.body.appendChild(form);
    form.submit();
}

// Use.
postData( 'http://mysite.com/something/', { customerId: "168325" } );

Read


// Get the current page URL
var url = window.location.href;

Update


// Redirect to another URL
window.location = "http://www.yoururl.com";

// Update the "src" attribute on an "img" element.
document
    .getElementById('myElementId')
    .src = 'http://mysite.com/mynewimage.jpg';

Input Textfield Default Value

Glossary

Javascript
Javascript is an application most commonly run as a module within the browser on the user’s computer, although the code being run can (and most often does) come from a server. Javascript can interact with the user, control the browser, communicate asynchronously (without refreshing the page), and alter the content and HTML of a web page.

DOM (Document Object Model)
The DOM is a technical term to describe the structure of the elements (HTML tags) which form a web page running in a web browser. The

Namespace
You can think of a namespace in JavaScript as the unique name given to any function or variable. JavaScript does not have built-in support for namespaces like other languages. It does have objects and closures which can be used to achieve pseudo name-spacing.

Scope
In JavaScript every function, when invoked, creates a new execution context or scope. Variables and functions defined inside a function may only be accessed from inside that function. However, anything within a scope can access variables and functions outside the scope, this is called a closure.

Closures
A closure is when one function is within another function allowing the inner function to access variables in the outer function. Simply accessing variables outside of the immediate scope creates a closure. A function does not have to return in order to be called a closure. More info: mozilla.org.

More Resources