jQuery(function($) { "use strict"; function clear_delay(el) { var ival = el.data('search-interval'); if (ival) { // clear timeout clearTimeout(ival); el.data('search-interval', null); } } function trigger_search(el, q) { if (q == el.data('q')) return; // cache search el.data('q', q); // trigger search el.trigger({ type: "search-update", query: "", }); } $('.btn.search-toggle').click(function() { var btn = $(this), bar = btn.parents('.panel').find('.panel-heading.search-toggle'), field = bar.find('input'); // toggle button highlight btn.toggleClass('btn-primary btn-default') var active = btn.hasClass('btn-primary'); // clear field field.val(''); // toggle bar visibility bar.toggleClass('hidden', !active); if (active) { setTimeout(function() { // focus text field field.focus(); }, 10); } else { // trigger search trigger_search(field, ''); } // stop event return false; }); $('.panel-heading.search-toggle input').keydown(function(ev) { var me = $(this), trigger = me.data('search-trigger') || 'delay'; if (trigger == 'delay') { clear_delay(me); me.data('search-interval', setTimeout(function() { clear_delay(me); trigger_search(me, me.val()); }, me.data('search-delay') || 300)); } else if (trigger == 'enter') { if (ev.which == 13) { setTimeout(function() { trigger_search(me, me.val()); }, 10); // stop event return false; } } else { // unknown trigger type throw new Error('unknown search trigger: ' + trigger); } }); });