jquery snippets

How to implement collapsible content (folders, categories, jimmy the cat) with jQuery

Tagged collapse, expand, jquery, folder, category  Languages javascript

This here is a quick-and-dirty implementation of folders for jQuery:

Markup

Any markup following the naming conventions should work, for example:

<ul class="collapsible">
  <li>
     <a href="" class="toggle-button">This be the folder</a>
    <ul style="display:none" class="collapsible-content">
        <li>This be the folder content</li>
        <li>This be the folder content</li>
    </ul>
  </li>
</ul>

JavaScript

/**
 * Collapsible categories implementation.
 * 
 */
var category = {
  find_category: function(target) {
    var category = target;
    // This isn't the category, so look for it
    if(!target.hasClass('collapsible')) {
      category = target.closest('.collapsible');
    }
    return category;
  },
  collapse: function(target) {
    var category = this.find_category(target);
    category.find('.collapsible-content').hide();
    category.removeClass('expanded');
    category.addClass('collapsed');
  },
  expand: function(target) {
    var category = this.find_category(target);
    category.find('.collapsible-content').show();
    category.addClass('expanded');
    category.removeClass('collapsed');
  },
  toggle: function(target) {
    var category = this.find_category(target);

    var is_expanded = category.hasClass('expanded');

    if(is_expanded) {
      this.collapse(category);
    } else {
      this.expand(category);
    }
  }
}

Usage

$('.toggle-button').live('click', function() {
  category.toggle($(this));
  return false;
});

How to parse request parameters with JavaScript

Tagged javascript, jquery, request, parameters, url, parse  Languages javascript

Code:

var Request = {
    parameter: function(name) {
      return this.parameters()[name];
    },
    parameters: function(uri) {
      var i, parameter, params, query, result;
      result = {};
      if (!uri) {
        uri = window.location.search;
      }
      if (uri.indexOf("?") === -1) {
        return {};
      }
      query = uri.slice(1);
      params = query.split("&");
      i = 0;
      while (i < params.length) {
        parameter = params[i].split("=");
        result[parameter[0]] = parameter[1];
        i++;
      }
      return result;
    }
  };

Examples:

// ?query=test
var query = Request.parameter('query');

var parameters = Request.parameters();
// This works too
var query = parameters.query;
// And this
var query = parameters['query'];

// Replacing a parameter is easy with jQuery
parameters Request.parameters();
// change sort order
parameters.order = 'new-world-order'
new_parameters = $.param(parameters)
url = window.location.pathname + "?" + new_parameters

How to prevent double form submissions with jQuery

Tagged jquery, submit, ajax  Languages javascript

This snippet will disable the submit button after the user clicks on it:

$('form').submit(function(){
    var $button = $('input[type=submit]', this);
    $button.attr('disabled', 'disabled');
    $button.attr('value', $button.attr('value') + "...");
});

For Ajax forms, you need to enable the button again in your code.

How to create a JSONP cross-domain webservice with Sinatra and Ruby

Tagged json, sinatra, jquery, jsonp  Languages ruby

Your Sinatra app:

get '/' do
    callback = params.delete('callback') # jsonp
    json = {'your' => 'data'}.to_json

    if callback
      content_type :js
      response = "#{callback}(#{json})" 
    else
      content_type :json
      response = json
    end
    response
  end

Your HTML:

<script type="text/javascript">
    function parseResponse(json) {
    // Do something with the data
    }
    </script>
    <script type="text/javascript" src="http://xxx.com/?callback=parseResponse"></script>

You can also do the same with jQuery:

$.ajax({
    type: 'get',
    url: '/',
    dataType: 'jsonp',
    success: function(data) {
      parseResponse(data);
    }
})

How to parse XML feeds with jQuery

Tagged feed, internet explorer, jquery, atom, rss, parse  Languages javascript
$.ajax({
    type: 'GET',
    url: '/some/good/stuff.xml',
    dataType: 'xml',
    error: function(xhr) {
        alert('Failed to parse feed');
    },
    success: function(xml) {
        var channel = $('channel', xml).eq(0);
        var items = [];
        $('item', xml).each( function() {
            var item = {};
            item.title = $(this).find('title').eq(0).text();
            item.link = $(this).find('link').eq(0).text();
            item.description = $(this).find('description').eq(0).text();
            item.updated = $(this).find('pubDate').eq(0).text();
            item.id = $(this).find('guid').eq(0).text();
            items.push(item);
        });
        console.dir(items);
    }
});

Your friend Internet Explorer

For IE 6 and better (worse?) the feed must return the right content type, so make sure the response contains this header:

Content-type: text/xml

If this header is not set the jQuery Ajax error handler is called and the feed is not parsed.

How to build popup menus and tooltips with jQuery

Tagged menu, hover, tooltip, contextmenu, jquery, popup  Languages javascript

This snippet shows you how to build a simple popup menu with jQuery. The example code can also be used to build things such as tooltips.

In the example we're going to build a menu for deleting table rows.

The HTML:

<table id="data">
  <tr>
    <td>
      <a href='/domains/digg.com'>digg.com</a>
      <!-- menu start -->
      <span class='hover-menu'>
        <a href='/domains/digg.com/remove' class='remove'>remove</a>
      </span>
      <!-- menu end -->
    </td>
  </tr>
</table>

The CSS:

.hover-menu
  display: none

The Javascript:

$.event.special.hover.delay = 200; 
$.event.special.hover.speed = 200; 

var show = function(e) {
  var $this = $(this);
  var $tooltip = $this.find('.hover-menu');
  $tooltip.fadeIn();
}

var hide = function() {
  var $this = $(this);
  var $tooltip = $this.find('.hover-menu');
  $tooltip.fadeOut();
}
$('#data td').bind('hover', show);
$('#data td').bind('hoverend', hide);

When you hover your mouse over table rows the menu will be shown.

You'll need to install the Event hover jQuery plugin to be able to use the hover and hoverend events. You could replace them with mouseenter and mouseleave, but usability would suffer...

jQuery increment/decrement plugin

Tagged jquery, increment, decrement  Languages javascript

With the jQuery increment-decrement plugin:

(function($){  
  /**
   * Returns the current value of the counter.
   */
  function value(counter) {
    return parseInt(counter.html());
  }
  /**
   * Changes the counter's value.
   */
  function change(counters, step) {
    return counters.each(function() {  
      var $counter = $(this);
      // Increment counter
      var count = value($counter) + step;
      $counter.html(count);
      // Trigger event
      var event_name = step > 0 ? 'increment' : 'decrement';
      $counter.trigger(event_name, [$counter, count]);
      return count;
    });  
  }
  $.fn.increment = function(step) {  
    if(!step) { step = 1; }
    change(this, step);
  };  
  $.fn.decrement = function(step) {  
    if(!step) { step = -1; }
    change(this, step);
  };  
  $.fn.counterValue = function() {  
    return value($(this));
  };  
})(jQuery);

and the following HTML:

<div id="counter">0</div>

you can call these methods to increment/decrement the number:

$('#counter').increment();
$('#counter').increment(10)
$('#counter').decrement();
$('#counter').decrement(-10)

Event listeners

You can also listen to the increment and decrement events:

$('#counter').bind('increment', function(event, counter, value) {
  console.log('Incremented ' + counter + value);
});
$('#counter').bind('decrement', function(event, counter, value) {
  console.log('Decremented ' + counter + value);
});

jQuery cycle plugin

Tagged jquery, cycle  Languages javascript
(function($){  
  $.fn.cycle = function() {
    $(this).each(function(index) {
      var cls = index % 2 ? 'even':'odd';
      $(this).attr('class', cls);
    });
  }
})(jQuery);

Highlighting page elements with jQuery and the jquery-color plugin

Tagged jquery, ajax, plugin, highlight  Languages javascript

This plugin is useful for making the user aware of changes to the page. It does this through an animated effect that changes the matching element's color to light yellow and then back to transparent.

You need the jquery-color plugin and the highlight plugin:

// http://github.com/jquery/jquery-color
(function(d){d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(f,e){d.fx.step[e]=function(g){if(!g.colorInit){g.start=c(g.elem,e);g.end=b(g.end);g.colorInit=true}g.elem.style[e]="rgb("+[Math.max(Math.min(parseInt((g.pos*(g.end[0]-g.start[0]))+g.start[0]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[1]-g.start[1]))+g.start[1]),255),0),Math.max(Math.min(parseInt((g.pos*(g.end[2]-g.start[2]))+g.start[2]),255),0)].join(",")+")"}});function b(f){var e;if(f&&f.constructor==Array&&f.length==3){return f}if(e=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(f)){return[parseInt(e[1]),parseInt(e[2]),parseInt(e[3])]}if(e=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(f)){return[parseFloat(e[1])*2.55,parseFloat(e[2])*2.55,parseFloat(e[3])*2.55]}if(e=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(f)){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}if(e=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(f)){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}if(e=/rgba\(0, 0, 0, 0\)/.exec(f)){return a.transparent}return a[d.trim(f).toLowerCase()]}function c(g,e){var f;do{f=d.curCSS(g,e);if(f!=""&&f!="transparent"||d.nodeName(g,"body")){break}e="backgroundColor"}while(g=g.parentNode);return b(f)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]}})(jQuery);

// Highlight plugin
(function($){  
  $.fn.highlight = function(color) {
    $(this).each(function(index) {
      // Use default color if no color is specified
      if(!color) {
        color = "#faff99";
      }
      var $this = $(this);
      // We restore the original color at the end
      var original = $this.css('background-color');
      $this.animate({ backgroundColor: color }, 500)
      $this.animate({ backgroundColor: original }, 500)
    });
  }
})(jQuery);

To use the plugin use the following code:

$("table tr:first").highlight();

This will highlight the first row in the table.

You can also specify a color:

$("table tr:first").highlight('#ccc');

How to add and remove validation rules (jQuery validate plugin)

Tagged jquery, validation, plugin, remove, add  Languages javascript

This snippet shows how to change the jQuery validation plugin's validation rules dynamically:

$(document).ready(function() { 
  // Setup the default validation rules
  var validator = $('form').validate({ 
    rules: { 
      username: { 
        required: true, 
        minlength: 2
      }
    }
  };

  // Drop-down selection changes validation rules
  $('#account-type').change(function () {
    // Get the jQuery validation plugin's settings
    var settings = $('form').validate().settings;

    // Modify validation settings
    $.extend(true, settings, {
       rules: {
           // Add validation of year
           "year": {
               required: true,
               min: 2010,
               max: 2020,
               number: true
           }, 
           // Remove validation of username
           "username": {} 
       }
    });
  });
});

You can also use CSS classes to achieve the same:

$('#channel-title').addClass("{required:true,messages:{required:'required field'}}")
$('#channel-title').removeClass("{required:true,messages:{required:'required field'}}")