jquery snippets

How to create an autocompleted field with jQuery, which looks and feels like autocomplete with Scriptaculous & prototype

Tagged jquery, autocomplete, plugin, scriptaculous, prototype  Languages javascript

There are a lot of autocomplete plugins for jQuery, but not one of them seems to work similarly to Scriptaculous, except for the one at bassistance.de.

To use it follow the instructions found here.

There are a couple of gotchas for ex-scriptaculous users, like that the controller should return the list of tags with a newline character as separator, compared to an HTML list with Scriptaculous.

The other gotcha is the syntax, which is a lot prettier than Scriptaculous:

<script type="text/javascript">
$("#tags-field").autocomplete("/tags/autocomplete", {
    multiple: true,
    autoFill: true,
    minChars: 3

Remember that /tags/autocomplete should render a list of tags delimited by linefeeds:


Note that jQuery sends the user typed text in a request parameter named 'q', so jQuery makes the following request to your controller: '/tags/autocomplete?q=ruby'.

The list that's shown when you type something can be styled with these CSS rules:

div.ac_results {
    width: 350px;
    background: #fff;

div.ac_results ul {
    border:1px solid #888;

div.ac_results ul li {

// Hovering over list item
div.ac_results ul li.ac_over {
    background-color: #ffb;

The plugins documentation is quite good, but for some reason it was easier to figure out what was needed to get it working by reading the code.

Getting the state of checkboxes with jQuery

Tagged jquery, checkbox  Languages javascript

The following code will loop through all selected (checked) checkboxes and collect their values in an array:

var selected = [];
$('#select-columns input[@type=checkbox]').filter(':checked').each(function () {

More examples can be found here

Really simple hover menus with jQuery

Tagged jquery, hover, menu, simple  Languages javascript

I got the inspiration for this simple menu from this blog post. It's based on the hover intent jQuery plugin by Brian Cherne.

The requirements:

Hide menu on mouse out:


Display menu on mouse over:





<div id="categories-menu" class="hover-menu">
  <ul class="actions no-style" style="display: none">
    <li><a href="">Add</a></li>
    <li><a href="">Edit</a></li>
    <li><a href="">Delete</a></li>

The JavaScript

<script type="text/javascript">
$(document).ready(function() {

  function show() {
    var menu = $(this);
  function hide() { 
    var menu = $(this);

    sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
    interval: 50,   // number = milliseconds for onMouseOver polling interval
    over: show,     // function = onMouseOver callback (required)
    timeout: 300,   // number = milliseconds delay before onMouseOut
    out: hide       // function = onMouseOut callback (required)

Positioning the hover menu over the content

The above example will show the menu inline with the content, effectively pushing it down. To avoid that, use this HTML:

<div id="categories-menu" class="hover-menu" style="position: relative">
  <ul class="actions no-style" style="position: absolute; background: white; display: none;">
    <li><a href="" id="edit-mode">Edit mode</a></li>
    <li><a href="" class="last">Add</a></li>

hoverIntent alternative

See this snippet for an alternative solution.

How to use jQuery with Rails 2.0 - aka How to fix "ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken)"

Tagged authenticity, rails, rails 2, token, jquery, javascript, ajax  Languages ruby

This is a slight variation of Henrik Nyh's code, which fixes an issue with IE6 that makes all Ajax requests use POST in IE6.

In application.html.erb, or whatever layout file you're using, put:

<%= javascript_tag "window.AUTH_TOKEN = '#{form_authenticity_token}';" %>

In application.js, or whatever JavaScript file you're using, put:

$(document).ajaxSend(function(event, request, settings) {
  if (typeof(window.AUTH_TOKEN) == "undefined") return;
  // IE6 fix for http://dev.jquery.com/ticket/3155
  if (settings.type == 'GET' || settings.type == 'get') return;

  settings.data = settings.data || "";
  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(window.AUTH_TOKEN);

That's all...

Showing ActiveRecord error messages from jQuery Ajax actions and scripts

Tagged ajax, error, jquery, rails  Languages ruby

The HTML, in a layout file, for example application.html.erb:

<div id="error-message" style="display:none">

The JavaScript, rendered by for example create.js.erb:

<% if !@category.valid? %>
  errors = <<ERR
  <p>Please fix the following errors:</p>
    #{@category.errors.collect{|err| "<li>" + err[0] + " " + err[1] + "</li>" } }
$('#error-message').html('<%= escape_javascript(errors) %>');
<% else %>
<% end %>

How to display an animated icon during Ajax request processing

Tagged ajax, jquery, indicator, loading  Languages javascript

This example uses the jQuery JavaScript library.

First, create an Ajax icon using the AjaxLoad site.

Then add the following to your HTML:

<img src="/images/loading.gif" id="loading-indicator" style="display:none" />

And the following to your CSS file:

#loading-indicator {
  position: absolute;
  left: 10px;
  top: 10px;

Lastly, you need to hook into the Ajax events that jQuery provides; one event handler for when the Ajax request begins, and one for when it ends:

$(document).ajaxSend(function(event, request, settings) {

$(document).ajaxComplete(function(event, request, settings) {

How to track user actions and custom events with Google Analytics and jQuery

Tagged jquery, google, analytics, track, click  Languages javascript

This is a customization of Rebecca Murphey's script:

$('a').each(function() {
    var $a = $(this);
    var href = $a.attr('href');
    if(typeof pageTracker == 'undefined') { return; }

    // Link is external
    if (href.match(/^http/) && !href.match(document.domain)) {
        $a.click(function() {
            pageTracker._trackPageview('/external/' + href);
    } else {
        $a.click(function() {
            pageTracker._trackPageview('/internal' + href);

Note that clicks are shown as page views in reports, so you should exclude them from all reports. A future version of Google Analytics will allow you to track events, such as mouse clicks, without affecting page view reporting, see this page on the new event tracking beta feature for more information.

DELETE, PUT, GET and POST with jQuery

Tagged delete, put, get, post, jquery  Languages javascript

Example of how to do DELETE, PUT, GET and POST with jQuery and Rails REST type routing:

    type: 'get', 
    url: '/subscriptions/' + id,
    data: "subscription[title]=" + encodeURI(value),
    dataType: 'script' 

    type: 'POST', 
    url: '/subscriptions/' + id,
    data: "subscription[title]=" + encodeURI(value),
    dataType: 'script' 

    type: 'PUT', 
    url: '/subscriptions/' + id,
    data: "subscription[title]=" + encodeURI(value),
    dataType: 'script' 

    type: 'DELETE',
    url: url,
    data: 'subscription[id]=' + id,
    dataType: 'script'

The gotcha with DELETE is to specify the ID using the data parameter, otherwise you might get this error; at least with Rails 2.2.2, jQuery 1.3.1, FF 3:

/!\ FAILSAFE /!\  Mon Feb 16 13:57:52 +0200 2009
  Status: 500 Internal Server Error
  You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.attributes
    /usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/vendor/xml-simple-1.0.11/xmlsimple.rb:708:in get_attributes'
    /usr/lib/ruby/gems/1.8/gems/activesupport-2.2.2/lib/active_support/vendor/xml-simple-1.0.11/xmlsimple.rb:462:in collapse'

Positioning an element over another element with jQuery

Tagged jquery, position, absolute, tooltip, dialog  Languages javascript

Positioning an element over another element is a common problem and can be used for creating simple tooltips, inline dialogs, informational messages and so on.

The code is simple:

$.fn.positionOn = function(element, align) {
  return this.each(function() {
    var target   = $(this);
    var position = element.position();

    var x      = position.left; 
    var y      = position.top;

    if(align == 'right') {
      x -= (target.outerWidth() - element.outerWidth());
    } else if(align == 'center') {
      x -= target.outerWidth() / 2 - element.outerWidth() / 2;

      position: 'absolute',
      zIndex:   5000,
      top:      y, 
      left:     x



Normally you would use this code within an event listener such as mouseover or click:

$(".add-link").live('click', function(event) {
      var target = $(this);
      var dialog = $('#add-link-dialog');

      dialog.positionOn(target, 'center');

      return false;

More examples:

# Default is align with top left corner of given element
# But you can align to the right and center
$('#add-link-dialog').positionOn($('.add-link'), 'right')
$('#add-link-dialog').positionOn($('.add-link'), 'center')

You'll need the jQuery dimensions plugin for this to work.