I have a postcode field that has a jQuery onKeyup event - the idea is that once they have fully entered their postcode to call an Google Maps Geocoding API to get the location immediately based on this postcode.
This code works however i'd like to find a solution that will ideally not call the API multiple times but wait and see if the user has finished typing using some method of waiting for x amount of time and then calling the API.
Can anyone suggest the best way to do this?
$("#txtPostcode").keyup(function() {
var postcode = $('#txtPostcode').val().length
if (postcode.length >= 5 && postcode.length <= 8) {
console.log('length is a valid UK length for a postcode');
// some logic here to run with some way to work out if user has 'finished' typing
callGoogleGeocodingAPI(postcode);
}
});
This is done to ensure that the variable doesn't contain any pre-existing timeout before assigning a new timeout to it. Thereafter, a new timeout is created with the setTimeout() method to add the delay after the keypress() function which generates the desired effect i.e. keyup with a delay.
The keyup event is sent to an element when the user releases a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus. Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.
KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.
You can use setTimeout
to only make the call after typing has stopped for 250ms - this is generally enough time between keystrokes to allow the full entry. Try this:
var timer;
$("#txtPostcode").keyup(function() {
clearTimeout(timer);
timer = setTimeout(function() {
var postcode = $('#txtPostcode').val().length
if (postcode.length >= 5 && postcode.length <= 8) {
console.log('length is a valid UK length for a postcode');
// some logic here to run with some way to work out if user has 'finished' typing
callGoogleGeocodingAPI(postcode);
}
}, 250);
});
You can tweak the exact timeout to better suit your needs if you feel there is too much of a delay.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With