Skip to content

Instantly share code, notes, and snippets.

@wei
Last active June 16, 2022 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wei/6522267819fa0aeecc5a836974db428b to your computer and use it in GitHub Desktop.
Save wei/6522267819fa0aeecc5a836974db428b to your computer and use it in GitHub Desktop.
Google Maps API AutoComplete Auto Select First on Enter
selectFirstOnEnter(input){
const _addEventListener = input.addEventListener;
let hasHitDown = false;
// Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected, and then trigger the original listener.
function addEventListenerWrapper(type, listener) {
if (type === "keydown") {
var orig_listener = listener;
listener = function (event) {
if (event.which === 13) {
if (!hasHitDown) {
const eventObj = document.createEvent("Events");
eventObj.initEvent("keydown", true, true);
eventObj.which = 40;
eventObj.keyCode = 40;
input.dispatchEvent(eventObj);
}
hasHitDown = false;
} else if (event.which === 40) {
hasHitDown = true;
}
orig_listener.apply(input, [event]);
if (event.which === 13) {
input.blur();
}
};
}
// add the modified listener
_addEventListener.apply(input, [type, listener]);
}
input.addEventListener = addEventListenerWrapper;
}
@dzung1nguyen
Copy link

You save my time. Thanks
Also, we have small updating with initEvent
Replace:
const eventObj = document.createEvent("Events");
eventObj.initEvent("keydown", true, true);
To
const eventObj = new Event("keydown", {
bubbles: true,
cancelable: true,
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment