JavaScript: code organization template

If not working with a framework, try the following: $(function() { function MyFunction() { } MyFunction.prototype = { myMethod: function() { } }; var myInstance = new MyFunction(); }); If you are looking for something simpler, kind of a one quick page deal: var GLOBAL_NAMESPACE_HERE = (function () { var _private_obj_name_here = { // settings […]

javascript: when scope inside setTimeOut is giving you headaches

Sometimes you have to setTimeOut call a function, but you need to provide the current scope for the function to execute as well. Say for example, you want to call this.myFunction() with (this) { setTimeout( function() { myFunction() }, 1000 );} Doing the with(this) allows you to pass “this” scope, so myFunction will get executed […]

Javascript patterns: namespacing your objects.

Avoid clustering the global scope. Start with uppercase (recommended): var MYAPP = MYAPP || {}; To be able to construct objects with several levels of deepness, use the following utility function: var UTILITIES = UTILITIES || {}; UTILITIES.namespace = function (ns_string) { var parts = ns_string.split(‘.’), parent = MYAPP, i; // strip redundant leading global […]

Javascript and scrollbars

To detect if the scrollbar is all the way to the top: var scrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop; if(scrollY == 0){ /* Scroll at top, do something here */ } Infinite scroll implementation: $(window).scroll(function(){ if(($(window).scrollTop() + 100) > ($(document).height() – $(window).height())){ /* You are 100px close to the bottom scroll, load more content […]