HTML Dog
Skip to navigation

jQuery: Other Tricks

jQuery also helps you out with other common tasks, particularly where things are inconsistent across browsers.

DOMContentLoaded

Sometimes you will want to run JavaScript only when the DOM is loaded and ready (but before stylesheets are fully loaded) - for example, to move elements to a different location in the page, or create new ones. We can do this in pure JavaScript (although this will not work in all browsers):


var doSomething = function (event) { . . . };

window.addEventListener('DOMContentLoaded', doSomething);

But we can do it more easily with jQuery, and it will work cross-browser:


$(window).ready(doSomething);

This can be shortened further to:


$(doSomething);

In all the above examples, doSomething is a JavaScript function.

Load

In other situations it’s better to wait for the page to fully load - that is, when all stylesheets and images have been downloaded.

To do this without jQuery, listen for the load event on the window:


window.addEventListener('load', doSomething);

But it’s even easier with jQuery:


$(window).load(doSomething);

Type checking

Finding out what kind of data is stored in a variable in JavaScript is awkward at best so jQuery provides some tools to help you out:


$.isArray([1, 2, 3]);

true

$.isFunction(function () { });

true

$.isNumeric(10);

true

$.isPlainObject({ name: 'Tom' });

true