Last active
December 25, 2015 14:39
-
-
Save jtenner/6992658 to your computer and use it in GitHub Desktop.
Requires Underscore: Ajax dropdown list pattern for bootstrap and lodash. This snippet will fire your ajax event for a dropdown-menu on a text box only after waiting 400 ms for the last input. Afterwards it hooks up a click event to the body to close the dropdown. Yes, I used jquery. No, it isn't required. I personally prefer vanilla javascript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
var debouncedKeyPress; | |
function wrapper(e){ | |
var keycode = e.keyCode||e.which; | |
debouncedKeyPress(this); | |
if(keycode === 13)//prevent form submission | |
{ | |
e.preventDefault(); | |
return false; | |
} | |
} | |
function keypress(caller){ | |
//perform ajax query here | |
//$.get(url, callback) have callback fill the ul | |
var parent = $(caller).parent('.dropdown'); | |
var list = parent.find('.dropdown-menu'); | |
//open the menu | |
parent.addClass('open'); | |
//empty the menu for the callback | |
list.html(''); | |
$('body').click(function(){ | |
hideMenu(caller); | |
$('body').off('click'); | |
}); | |
} | |
function hideMenu(caller){ | |
//All done, clean up | |
var parent = $(caller).parent('.dropdown'); | |
parent.removeClass('open'); | |
} | |
debouncedKeyPress = _.debounce(keypress, 400); | |
})() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment