$(document).ready(function () { // live search $('#pm-search').typeWatch({ callback: function() { $.ajax({ type: "POST", url: MELODYURL2 + "/ajax-search.php", data: { "queryString": $('#pm-search').val() }, dataType: "html", success: function(b){ if (b.length > 0) { $(".pm-search-suggestions-list").html(b); $(".pm-search-suggestions").show(function() { var $listItems = $('.pm-search-suggestions-list').find('li'); $('#pm-search').keydown(function(e) { var key = e.keyCode, $selected = $listItems.filter('.selected'), $current; if ( key === 27 ) { // ESC $(".pm-search-suggestions").hide(); } if( key == 38 || key == 40 ){ // UP/DOWN e.preventDefault(); } if ( key != 38 && key != 40 ) return; $listItems.removeClass('selected'); if ( key == 40 ) // Down key { if ( ! $selected.length || $selected.is(':last-child') ) { $current = $listItems.eq(0); } else { $current = $selected.next(); } } else if ( key == 38 ) // Up key { if ( ! $selected.length || $selected.is(':first-child') ) { $current = $listItems.last(); } else { $current = $selected.prev(); } } $current.addClass('selected'); $selected_url = $current.find('a').attr('href'); $selected_id = $current.attr('data-video-id'); ($('#pm-video-id').val($selected_id)); }); $(document).on('click', (function(e) { if(e.target.className !== "pm-search-suggestions" && e.target.id !== "pm-search") { $(".pm-search-suggestions").hide(); }})); }); } else { $(".pm-search-suggestions").hide(); } } }); }, wait: 400, highlight: true, captureLength: 3 }); });