27 Aug 2011

Some Simple jQuery Plugins

Below are some really simple jQuery plugins that I've thrown together over the past couple of years that I've found useful.

Need to scroll to element with animation? Here you go:

  // scroll to animation
  // example usage: $('.scroll_to_here').scrollTo();

  jQuery.fn.scrollTo = function(speed) {
    if(speed === undefined ){
      speed = 'slow';
    }
    $('html,body').animate({scrollTop: this.offset().top},speed);
  };

Ajax polling is pretty easy with jQuery, but it is nice to have reusable function so you don't repeat yourself. The plugin below is based on another simple ajax polling plugin that scales the amount of time between requests. This plugin uses a simple interval with a maximum number of attempts.

  //Simple AJAX Polling jQuery Plugin
  // example usage:
  /* $.ajaxPoll({
          url: "/path",
          type: "GET",
          interval: 250,
          maxAttempts: 25,
          successCondition: function(result) {
              return result != "processing"; 
          },
          success: function(data) {
              $('#container').replaceWith(data);
          }
      });
  */

  jQuery.ajaxPoll = function(user_options){

    var options = {
      interval: 30000,
      maxAttempts: 15
    }
  
    jQuery.extend(options, user_options);
  
    var attempts = 0;

    options.success = function(data, status) {

      if (options.successCondition(data)) {
          if (options.successCallback){
            options.successCallback(data, status);
          }          
          return;
      }
    
      attempts++;

      if (attempts > options.maxAttempts) {
          return;
      }
    
      setTimeout(function() { jQuery.ajax(options) }, options.interval);
    };

    jQuery.ajax(options);
  }

The HTML5 placeholder attribute is awesome, but some browsers (IE and ... maybe just IE?) do not support it. Here is a jQuery plugin that solves that problem by clearing and restoring a field's placeholder value in browsers that don't handle that silliness for you.

  // clears and restores a field's default value
  // example usage (js): $('input.has_default').hasDefaultValue();
  // example usage (html): <input class="has_default" placeholder="This is displayed by default" type="text"/>

  jQuery.fn.hasDefaultValue = function() {
    function supports_input_placeholder() {
      var i = document.createElement('input');
      return 'placeholder' in i;
    }
    if(!supports_input_placeholder()){
      this.each(function(){
        if(this.value === ""){
          this.value = $(this).attr("placeholder")
        }
      });
      this.focus(function(event){
        if(this.value === $(this).attr("placeholder")){
          this.value = ""
        }
      })
      this.blur(function(event){
        if($(this).attr("placeholder") && this.value === ""){
          this.value = $(this).attr("placeholder");
        } 
      })
    }
  };