Put all your JS within an anonymous function using the following template
(function ($) {
'use strict';
// global variables go here
var foo, bar;
// put code that can be executed before the document is ready, e.g.
$(window).on('hashchange', function() {
foo = true;
}
$('#content').on('click', "a", function() {
foo = false;
}
// functions go here
function filterByCheckbox() {
}
function validate() {
// some code
$("input").trigger("validationPassed");
}
// put code that must/should be triggered after the document is ready
$(document).on ("ready", (function () {
// on load code goes here, e.g.
filterByCheckbox();
foo = true;
$('div.reports ul.tabs').append("abc");
// on event handlers (click, focus, submit, etc) go here, e.g.
$("select").on("change", function() {
// something
});
$("select").on("blur",validate);
$("select").on("validationPassed", function() {
// something
});
});
}(jQuery));
Put each separate code block that serves a separate purpose in a separate template above. Since Javascript is asynchronous, it can execute each code in each block / template simultaneously instead of one at a time.
Never trigger events using element.event(). Always use jQuery to handle events in a cross-browser way, e.g.
BAD
window.hashchange = function() {
}
GOOD
$(window).on('hashchange', function() {
});
For events, always use the jquery “on” and “off” functions to attach/bind and detach/unbind events. .live() is deprecated so use “on” with a subselector.
Normally, when you bind an event handler to an element, you do something like:
$("a").on('click', function (event) { ...
When binding event handlers to elements that are dynamically-generated, you’ll want to do it when the element is in the document, so use this format:
$(document).on('click', " a", function (event) { ...