Tutorial jQuery Sticky Footer

by in , 0

In general the CSS Sticky Footer is the best way to go, as it works perfectly smoothly and doesn't require JavaScript. If the markup required simply isn't possible, this jQuery JavaScript might be an option.

HTML

Just make sure the #footer is the last visible thing on your page.

<div id="footer">
    Sticky Footer
</div>

CSS

Giving it a set height is the most fool-proof.

#footer { height: 100px; }

jQuery

When the window loads, and when it is scrolled or resized, it is tested whether the pages content is shorter than the window's height. If it is, that means there is white space underneath the content before the end of the window, so the footer should be repositioned to the bottom of the window. If not, the footer can retain it's normal static positioning.

// Window load event used just in case window height is dependant upon images
$(window).bind("load", function() { 
       
       var footerHeight = 0,
           footerTop = 0,
           $footer = $("#footer");
           
       positionFooter();
       
       function positionFooter() {
       
                footerHeight = $footer.height();
                footerTop = ($(window).scrollTop()+$(window).height()-footerHeight)+"px";
       
               if ( ($(document.body).height()+footerHeight) < $(window).height()) {
                   $footer.css({
                        position: "absolute"
                   }).animate({
                        top: footerTop
                   })
               } else {
                   $footer.css({
                        position: "static"
                   })
               }
               
       }

       $(window)
               .scroll(positionFooter)
               .resize(positionFooter)
               
});

Demo

View Demo

Tutorial jQuery Plugin Template

by in , 0

Replace instances of "yourPluginName" with your actual plugin name. The stuff about "radius" is just an example of an option (parameter to pass plugin).

(function($){
    $.yourPluginName = function(el, radius, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;
        
        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el;
        
        // Add a reverse reference to the DOM object
        base.$el.data("yourPluginName", base);
        
        base.init = function(){
            if( typeof( radius ) === "undefined" || radius === null ) radius = "20px";
            
            base.radius = radius;
            
            base.options = $.extend({},$.yourPluginName.defaultOptions, options);
            
            // Put your initialization code here
        };
        
        // Sample Function, Uncomment to use
        // base.functionName = function(paramaters){
        // 
        // };
        
        // Run initializer
        base.init();
    };
    
    $.yourPluginName.defaultOptions = {
        radius: "20px"
    };
    
    $.fn.yourPluginName = function(radius, options){
        return this.each(function(){
            (new $.yourPluginName(this, radius, options));

		   // HAVE YOUR PLUGIN DO STUFF HERE
			
	
		   // END DOING STUFF

        });
    };
    
})(jQuery);

Usage

$(function() {

    $("#round-me").yourPluginName("20px");

});

Reference URL

Tutorial jQuery JSON getting with error catching

by in , 0

jQuery has a built in function called getJSON() to help making AJAX requests for JSON data easier. It normally works great, but if that function gets invalid data (or nothing) back, the callback function will not fire. If there is a legitimate risk of that, you can do this instead to catch for those errors.

$.get('/path/to/url', function (data) {
  if( !data || data === ""){
    // error
    return;
  }
  var json;
  try {
    json = jQuery.parseJSON(data);
  } catch (e) {
    // error
    return;
  }
  
  // use json here
  
}, "text");

Reference URL

Tutorial jQuery Duplicate Plugin

by in , 0

$.fn.duplicate = function(count, cloneEvents) {
       var tmp = [];
       for ( var i = 0; i < count; i++ ) {
               $.merge( tmp, this.clone( cloneEvents ).get() );
       }
       return this.pushStack( tmp );
};

The .clone() function of jQuery will duplicate a set once, but what if you need multiple copies of the same set? You would have to do:

$(elem)
   .clone()
   .appendTo(otherElem)
   .clone()
   .appendTo(otherElem)
   .clone()
   .appendTo(otherElem);

Now you can just:

$(elem)
   .duplicate(n)
   .appendTo(otherElem);

The first parameter is the number of clones you want and the second optional parameter is a boolean which controls if you want the events bound to those existing elements to be attached to the clones as well (or not).

Reference URL

Tutorial Insert Element Between Other Elements

by in , 0

For example, if you have five paragraphs in a row and you need to insert a break tag in between all of them. You can't put it before all five (you don't need one at the top) or after all five (you don't need one at the bottom), you only need four.

$("p:not(:last-of-type)").after("<br />");

Tutorial Inputs That Remember Original Value

by in , 0

var origValue = [];
$('input.remember').each ( function (currentIndex)
{
       origValue.push ( $(this).val () );
       $(this).focus ( function ()
       {
               $(this).removeClass("unfocused");
               var defaultText = $(this).val();
               if ( $(this).val () == origValue [ currentIndex ] )
               {
                       $(this).val('');
               }

               $(this).blur(function()
               {
                       var userInput = $(this).val();
                       if (userInput == '')
                       {
                               $(this).val(defaultText);
                               $(this).addClass("unfocused");
                       }
               });
       });
});

A jQuery snippet to make form inputs show a help message which disappears on click (and comes back when the user enters nothing). Give your input the classes 'remember' to activate the snippet and (optionally) 'unfocused' as a CSS hook for changing the styling of the help message.

Tutorial Image Preloader

by in , 0

Very easy way to preload images which are needed later (e.g. when a hover is performed)

<script type="text/javascript">
$.preloadImages = function()
{
       for(var i = 0; i<arguments.length; i++)
       {
               $("<img />").attr("src", arguments[i]);
       }
}

$(document).ready(function()
{
       $.preloadImages("hoverimage1.jpg","hoverimage2.jpg");
});
</script>