Code library

Free snippets & functions

Copy, adapt and use them in your own projects.

function loadProfile(userId) {
  return $.getJSON('/api/users/' + userId)
    .then(function (user) {
      return $.getJSON('/api/orders', { user: user.id || userId });
    })
    .then(function (orders) {
      return { count: (orders.items || []).length };
    });
}

loadProfile(7)
  .done(function (result) { $('#orders').text(result.count + ' orders'); })
  .fail(function () { $('#orders').text('Could not load'); });

Use the result of the first call to make the second, and handle every failure in one place.

jQuery · Run code for elements added laterAdvanced
function initTooltips(root) {
  $(root).find('[data-tip]').addBack('[data-tip]').not('.tip-ready').addClass('tip-ready').attr('title', function () {
    return $(this).data('tip');
  });
}

initTooltips(document);

new MutationObserver(function (mutations) {
  mutations.forEach(function (m) {
    $(m.addedNodes).filter(function () { return this.nodeType === 1; }).each(function () { initTooltips(this); });
  });
}).observe(document.body, { childList: true, subtree: true });

$('#content').append('<span data-tip="New tip">hover</span>');

Initialise your widgets on page load and again whenever new ones are added by AJAX.

jQuery · Keyboard shortcutsAdvanced
$(document).on('keydown', function (e) {
  const typing = $(e.target).is('input, textarea, select, [contenteditable]');
  const mod = e.ctrlKey || e.metaKey;

  if (mod && e.key.toLowerCase() === 'k') {
    e.preventDefault();
    $('#search').focus();
  } else if (!typing && e.key === '/') {
    e.preventDefault();
    $('#search').focus();
  } else if (!typing && e.key === '?') {
    $('#help').toggle();
  } else if (e.key === 'Escape') {
    $('#help').hide();
    $('#search').blur();
  }
});

Ctrl+K opens search, / focuses the box, ? shows help. Ignore shortcuts while typing in a field.

jQuery · Cache AJAX resultsAdvanced
const cache = {};

function cachedGet(url, params) {
  const key = url + '?' + $.param(params || {});
  if (cache[key]) return $.Deferred().resolve(cache[key]).promise();

  return $.getJSON(url, params).done(function (data) { cache[key] = data; });
}

cachedGet('/api/cities', { country: 'pk' }).done(function (d) { console.log('first (network)', d); });
setTimeout(function () {
  cachedGet('/api/cities', { country: 'pk' }).done(function (d) { console.log('second (cache)', d); });
}, 100);

Do not ask the server twice for the same data. Cache by URL and parameters.

function toggleDependents() {
  $('[data-show-if]').each(function () {
    const $box = $(this);
    const rule = String($box.data('show-if')).split('=');            // 'type=company'
    const current = $('[name="' + rule[0] + '"]:checked, select[name="' + rule[0] + '"]').val();
    const show = current === rule[1];

    $box.toggle(show);
    $box.find('input, select, textarea').prop('disabled', !show).prop('required', show && $box.data('required') !== false);
  });
}

$('form').on('change', 'input, select', toggleDependents);
toggleDependents();

Show a field only when it is needed, and make it required only while it is visible.

function paginate($table, perPage) {
  const $rows = $table.find('tbody tr');
  const pages = Math.max(1, Math.ceil($rows.length / perPage));
  const $nav = $('<nav class="pager">').insertAfter($table);

  function show(p) {
    $rows.hide().slice((p - 1) * perPage, p * perPage).show();
    $nav.find('button').removeClass('on').eq(p - 1).addClass('on');
  }

  for (let p = 1; p <= pages; p++) $('<button type="button">').text(p).appendTo($nav);
  $nav.on('click', 'button', function () { show($(this).index() + 1); });
  show(1);
  return { show: show, pages: pages };
}

const pager = paginate($('#big'), 10);

Show 10 rows at a time and build the page buttons from the data.

jQuery · A small carousel pluginAdvanced
(function ($) {
  $.fn.carousel = function (options) {
    const o = $.extend({ interval: 4000 }, options);
    return this.each(function () {
      const $c = $(this), $slides = $c.find('.slide');
      let i = 0, timer;

      function go(n) {
        i = (n + $slides.length) % $slides.length;
        $slides.removeClass('on').eq(i).addClass('on');
        $c.find('.dot').removeClass('on').eq(i).addClass('on');
      }
      function play() { if (o.interval) timer = setInterval(function () { go(i + 1); }, o.interval); }
      function stop() { clearInterval(timer); }

      $c.find('.next').on('click', function () { go(i + 1); });
      $c.find('.prev').on('click', function () { go(i - 1); });
      $c.on('click', '.dot', function () { go($c.find('.dot').index(this)); });
      $c.on('mouseenter focusin', stop).on('mouseleave focusout', play);
      go(0); play();
    });
  };
})(jQuery);

$('.carousel').carousel({ interval: 5000 });

Next, previous, dots and autoplay that pauses on hover. About forty lines.

jQuery · Save a new order after reorderingAdvanced
function saveOrder() {
  const ids = $('#items li').map(function () { return $(this).data('id'); }).get();
  $.post('/api/order', { ids: ids });
  try { localStorage.setItem('item-order', JSON.stringify(ids)); } catch (e) {}
  return ids;
}

function restoreOrder() {
  let ids = [];
  try { ids = JSON.parse(localStorage.getItem('item-order')) || []; } catch (e) {}
  $.each(ids, function (i, id) {
    $('#items').append($('#items li[data-id="' + id + '"]'));     // moves each to the end in saved order
  });
}

restoreOrder();

Collect the ids in their new order and send them to the server (or keep them in localStorage).

jQuery · A multi-step form wizardAdvanced
let step = 0;
const $steps = $('.step');

function show(n) {
  step = n;
  $steps.hide().eq(n).show();
  $('#progress').text('Step ' + (n + 1) + ' of ' + $steps.length);
  $('#back').toggle(n > 0);
  $('#next').text(n === $steps.length - 1 ? 'Finish' : 'Next');
}

$('#next').on('click', function () {
  const valid = $steps.eq(step).find('[required]').filter(function () { return !this.value.trim(); }).length === 0;
  if (!valid) return $('#msg').text('Please fill in this step.');
  $('#msg').text('');
  if (step === $steps.length - 1) return $('#wizard').trigger('submit');
  show(step + 1);
});
$('#back').on('click', function () { show(step - 1); });
show(0);

Validate each step before moving on. Show progress and keep Back available.

const $form = $('#profile');
const original = $form.serialize();
let saving = false;

$form.on('submit', function () { saving = true; });

$(window).on('beforeunload', function (e) {
  if (!saving && $form.serialize() !== original) {
    e.preventDefault();
    return (e.returnValue = 'You have unsaved changes.');
  }
});

$form.on('input change', function () {
  $('#save').prop('disabled', $form.serialize() === original);
});

Compare the current values with the original ones and ask before the user loses changes.

function poll(url, onData, opts) {
  const o = $.extend({ min: 2000, max: 30000 }, opts);
  let delay = o.min, timer, stopped = false, lastEtag = null;

  function run() {
    if (stopped) return;
    $.ajax({ url: url, dataType: 'json', ifModified: true, cache: false })
      .done(function (data, status) {
        if (status === 'notmodified') delay = Math.min(delay * 2, o.max);
        else { delay = o.min; onData(data); }
      })
      .fail(function () { delay = Math.min(delay * 2, o.max); })
      .always(function () { timer = setTimeout(run, delay); });
  }
  run();
  return { stop: function () { stopped = true; clearTimeout(timer); } };
}

const p = poll('/api/notifications', function (d) { $('#n').text(d.items.length); });
// p.stop();

Check for updates every few seconds. Slow down when nothing changes or when errors happen.

(function ($) {
  function Rating(el, options) {
    this.$el = $(el);
    this.opts = $.extend({ max: 5, value: 0 }, options);
    this.value = this.opts.value;
    this.render();
    this.$el.on('click.rating', 'span', $.proxy(this.onClick, this));
  }
  Rating.prototype.render = function () {
    const stars = [];
    for (let i = 1; i <= this.opts.max; i++) stars.push('<span data-v="' + i + '" class="' + (i <= this.value ? 'on' : '') + '">★</span>');
    this.$el.html(stars.join(''));
  };
  Rating.prototype.onClick = function (e) {
    this.value = $(e.currentTarget).data('v');
    this.render();
    this.$el.trigger('rating:change', [this.value]);
  };

  $.fn.rating = function (options) {
    return this.each(function () {
      if (!$.data(this, 'rating')) $.data(this, 'rating', new Rating(this, options));
    });
  };
})(jQuery);

$('.stars').rating({ max: 5 });

Each element gets its own instance, so several widgets on one page never share variables.

let $opener = null;

function openDialog($dlg, $from) {
  $opener = $from;
  $dlg.attr({ role: 'dialog', 'aria-modal': 'true' }).show().find('button, a, input').filter(':first').focus();

  $dlg.on('keydown.dlg', function (e) {
    if (e.key === 'Escape') return closeDialog($dlg);
    if (e.key !== 'Tab') return;
    const $f = $dlg.find('button, a[href], input, select, textarea');
    const first = $f.first()[0], last = $f.last()[0];
    if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
    else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
  });
}

function closeDialog($dlg) {
  $dlg.off('keydown.dlg').hide();
  if ($opener) $opener.focus();
}

Move focus into the dialog, keep Tab inside it and return focus to the button afterwards.

let active = -1;

$('#q').on('keydown', function (e) {
  const $items = $('#opts li');
  if (!$items.length) return;

  if (e.key === 'ArrowDown') active = (active + 1) % $items.length;
  else if (e.key === 'ArrowUp') active = (active - 1 + $items.length) % $items.length;
  else if (e.key === 'Enter' && active > -1) { $(this).val($items.eq(active).text()); $('#opts').empty(); active = -1; e.preventDefault(); return; }
  else if (e.key === 'Escape') { $('#opts').empty(); active = -1; return; }
  else return;

  e.preventDefault();
  $items.removeClass('hl').attr('aria-selected', 'false').eq(active).addClass('hl').attr('aria-selected', 'true');
  $(this).attr('aria-activedescendant', $items.eq(active).attr('id') || '');
});

Arrow keys move the highlight, Enter picks it, Escape closes the list. Needed for accessibility.

jQuery · Render HTML from data without XSSAdvanced
function esc(value) {
  return $('<div>').text(value).html();                       // browser does the escaping
}

function render(template, data) {
  return template.replace(/\{\{\s*(\w+)\s*\}\}/g, function (m, key) {
    return key in data ? esc(data[key]) : '';
  });
}

const tpl = '<li class="user"><b>{{ name }}</b> <small>{{ city }}</small></li>';
$('#users').append(render(tpl, { name: '<img src=x onerror=alert(1)>', city: 'Lahore' }));

Fill a template with escaped values. Never paste raw data into html().

$.fn.toJSONObject = function () {
  const result = {};
  $.each(this.serializeArray(), function (i, f) {
    const path = f.name.replace(/\]/g, '').split('[');          // user[name] -> ['user', 'name']
    let node = result;
    path.forEach(function (key, idx) {
      const last = idx === path.length - 1;
      if (key === '') { (node.__arr = node.__arr || []).push(f.value); return; }
      if (last) node[key] = f.value;
      else node = node[key] = node[key] || (path[idx + 1] === '' ? [] : {});
    });
  });
  (function fix(o) {
    $.each(o, function (k, v) { if (v && typeof v === 'object') fix(v); });
  })(result);
  return result;
};

$.ajax({ url: '/api/user', method: 'POST', contentType: 'application/json', data: JSON.stringify($('#f').toJSONObject()) });

Turns names like user[name] and tags[] into a real nested object, ready to send as JSON.

jQuery · A global event busAdvanced
const bus = $({});

const App = {
  on:  (name, fn) => bus.on(name, (e, ...args) => fn(...args)),
  off: (name) => bus.off(name),
  emit: (name, ...args) => bus.trigger(name, args),
};

App.on('user:login', (name) => $('#hello').text('Hello ' + name));
App.on('user:login', (name) => console.log('analytics:', name));

App.emit('user:login', 'Ali');

Use an empty object as a message bus, so modules never refer to each other directly.

jQuery · Tabs that follow the URL hashAdvanced
function openTab(hash, push) {
  const $pane = $(hash);
  if (!$pane.length || !$pane.hasClass('tab-pane')) hash = $('.tab-link:first').attr('href');
  $('.tab-pane').hide().filter(hash).show();
  $('.tab-link').removeClass('on').attr('aria-selected', 'false')
    .filter('[href="' + hash + '"]').addClass('on').attr('aria-selected', 'true');
  if (push && location.hash !== hash) history.pushState(null, '', hash);
}

$('.tab-link').on('click', function (e) { e.preventDefault(); openTab($(this).attr('href'), true); });
$(window).on('popstate', function () { openTab(location.hash, false); });
openTab(location.hash, false);

The address bar shows the open tab, so a link can open a specific tab and Back works.

jQuery · Upload with a progress barAdvanced
$('#upload-form').on('submit', function (e) {
  e.preventDefault();
  const $bar = $('#bar').css('width', 0);

  $.ajax({
    url: '/upload',
    method: 'POST',
    data: new FormData(this),
    processData: false,
    contentType: false,
    xhr: function () {
      const xhr = $.ajaxSettings.xhr();
      xhr.upload.addEventListener('progress', function (ev) {
        if (ev.lengthComputable) $bar.css('width', Math.round((ev.loaded / ev.total) * 100) + '%');
      });
      return xhr;
    },
  }).done(function () { $bar.css('width', '100%'); });
});

The xhr option lets you listen to the upload progress event.

jQuery · A drag-and-drop upload areaAdvanced
const $zone = $('#drop');

$zone.on('dragover dragenter', function (e) {
  e.preventDefault();
  $(this).addClass('over');
}).on('dragleave drop', function () {
  $(this).removeClass('over');
}).on('drop', function (e) {
  e.preventDefault();
  const files = e.originalEvent.dataTransfer.files;
  const fd = new FormData();
  $.each(files, function (i, f) {
    if (f.size <= 5 * 1024 * 1024) fd.append('files[]', f);
  });
  $.ajax({ url: '/upload', method: 'POST', data: fd, processData: false, contentType: false });
});

Drop files on the area. Check each one, then send them with FormData.

jQuery · Click to edit text in placeAdvanced
$(document).on('click', '.editable', function () {
  const $cell = $(this);
  if ($cell.find('input').length) return;
  const old = $cell.text();
  const $in = $('<input type="text">').val(old);
  $cell.empty().append($in);
  $in.focus().select();

  function finish(save) {
    const value = save ? $in.val().trim() : old;
    $cell.text(value || old);
    if (save && value && value !== old) {
      $.post('/api/update', { id: $cell.data('id'), field: $cell.data('field'), value: value });
    }
  }
  $in.on('keydown', function (e) {
    if (e.key === 'Enter') finish(true);
    if (e.key === 'Escape') finish(false);
  }).on('blur', function () { finish(true); });
});

Click a value to edit it, press Enter to save and Escape to cancel.

jQuery · Lazy-load images on scrollAdvanced
function lazyLoad() {
  const bottom = $(window).scrollTop() + $(window).height() + 200;
  $('img[data-src]').each(function () {
    if ($(this).offset().top < bottom) {
      $(this).attr('src', $(this).data('src')).removeAttr('data-src').addClass('loaded');
    }
  });
  if (!$('img[data-src]').length) $(window).off('scroll.lazy resize.lazy');
}

$(window).on('scroll.lazy resize.lazy', lazyLoad);
lazyLoad();

Set the real src only when the image is close to the screen.

jQuery · Infinite scrollAdvanced
let page = 1, loading = false, finished = false;

function loadMore() {
  if (loading || finished) return;
  loading = true;
  $('#more-spinner').show();

  $.getJSON('/api/posts', { page: ++page }).done(function (res) {
    const items = res.items || [];
    items.forEach(function (n) { $('<li>').text('Post ' + n).appendTo('#posts'); });
    if (items.length === 0) finished = true;
  }).always(function () {
    loading = false;
    $('#more-spinner').hide();
  });
}

$(window).on('scroll', function () {
  const nearBottom = $(window).scrollTop() + $(window).height() > $(document).height() - 300;
  if (nearBottom) loadMore();
});

Load the next page when the user is near the bottom. A flag prevents double loading.

jQuery · One place for all AJAX errorsAdvanced
$(document).ajaxError(function (event, xhr, settings) {
  if (settings.global === false) return;               // a request can opt out

  if (xhr.status === 401) {
    location.href = '/login?next=' + encodeURIComponent(location.pathname);
  } else if (xhr.status >= 500) {
    $('#toast').text('Server problem, please try again later.').fadeIn(200).delay(4000).fadeOut(200);
  } else if (xhr.status === 0 && xhr.statusText !== 'abort') {
    $('#toast').text('You seem to be offline.').fadeIn(200).delay(4000).fadeOut(200);
  }
});

Handle expired sessions and server errors once, for every request on the page.

// <meta name="csrf-token" content="abc123">
const token = $('meta[name="csrf-token"]').attr('content');

$.ajaxPrefilter(function (options, original, xhr) {
  const unsafe = !/^(GET|HEAD|OPTIONS)$/i.test(options.type || 'GET');
  const sameOrigin = !options.crossDomain;
  if (unsafe && sameOrigin) {
    xhr.setRequestHeader('X-CSRF-Token', token);
  }
});

$.post('/api/delete', { id: 5 });

Put the token in a meta tag and add it to every request that changes data.

let current = null;

function load(query) {
  if (current && current.readyState !== 4) current.abort();

  current = $.ajax({ url: '/api/search', data: { q: query }, dataType: 'json' })
    .done(function (res) { $('#results').text(res.items.length + ' results for ' + query); })
    .fail(function (xhr, status) {
      if (status === 'abort') return;                    // expected, not an error
      $('#results').text('Error');
    });
}

load('a');
load('ab');

Keep a reference to the running request. Cancel it before sending the next one.

function runSequence(jobs) {
  return jobs.reduce(function (previous, job) {
    return previous.then(function (results) {
      return job().then(function (data) {
        results.push(data);
        return results;
      });
    });
  }, $.Deferred().resolve([]).promise());
}

const rows = [{ id: 1 }, { id: 2 }, { id: 3 }];
const jobs = rows.map(function (row) {
  return function () { return $.post('/api/rows/' + row.id, row); };
});

runSequence(jobs).done(function (all) { console.log('saved', all.length); });

Each request starts only when the previous one finished. Useful for saving many rows in order.

jQuery · Debounce and throttle helpersAdvanced
$.debounce = function (fn, wait) {
  let t;
  return function () {
    const ctx = this, args = arguments;
    clearTimeout(t);
    t = setTimeout(function () { fn.apply(ctx, args); }, wait);
  };
};

$.throttle = function (fn, limit) {
  let last = 0;
  return function () {
    const now = Date.now();
    if (now - last >= limit) { last = now; fn.apply(this, arguments); }
  };
};

$(window).on('resize', $.debounce(function () { console.log('resize finished'); }, 200));
$(window).on('scroll', $.throttle(function () { console.log('scrolling'); }, 100));

Debounce waits until the events stop. Throttle runs at most once per interval.

jQuery · A plugin with methods and destroyAdvanced
(function ($) {
  const NAME = 'panel';
  const methods = {
    init(opts) {
      return this.each(function () {
        if ($(this).data(NAME)) return;
        const state = { open: false, opts: $.extend({ speed: 150 }, opts) };
        $(this).data(NAME, state).hide();
      });
    },
    open()  { return this.each(function () { $(this).data(NAME).open = true;  $(this).show(); }); },
    close() { return this.each(function () { $(this).data(NAME).open = false; $(this).hide(); }); },
    isOpen() { return !!this.first().data(NAME)?.open; },
    destroy() { return this.each(function () { $(this).removeData(NAME).off('.' + NAME).show(); }); },
  };

  $.fn[NAME] = function (method, ...args) {
    if (methods[method]) return methods[method].apply(this, args);
    if (!method || typeof method === 'object') return methods.init.call(this, method);
    $.error('Method ' + method + ' does not exist on jQuery.' + NAME);
  };
})(jQuery);

$('#p').panel().panel('open');

Call methods by name ($el.plugin('open')), keep state in data(), and clean up in destroy.

jQuery · A plugin with default optionsAdvanced
(function ($) {
  $.fn.counter = function (options) {
    const settings = $.extend({ start: 0, step: 1, onChange: $.noop }, options);

    return this.each(function () {
      const $el = $(this);
      let n = settings.start;
      $el.text(n).on('click', function () {
        n += settings.step;
        $el.text(n);
        settings.onChange.call(this, n);
      });
    });
  };
})(jQuery);

$('.counter').counter({ step: 5, onChange: (n) => console.log(n) });

Merge the caller's options over your defaults with $.extend, and keep the plugin chainable.