Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tweaking on keyup event to call API once it appears user has finished typing

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);
    }
});
like image 701
Zabs Avatar asked Jan 11 '16 10:01

Zabs


People also ask

How do I delay a Keyup event?

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.

What is the Keyup event?

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.

What is the difference between Keyup and Keydown?

KeyDown occurs when the user presses a key. KeyUp occurs when the user releases a key.


1 Answers

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.

like image 54
Rory McCrossan Avatar answered Sep 23 '22 17:09

Rory McCrossan