JavaScript

How to use pushState without breaking the back button

I find it very annoying when I use an instant search field and each key I press creates a new state. What this means every single time I hit the back button, it removes a single key from the URL. I have to press the back button a dozen times to get back to the previous page.

The better way to do it is to update the URL and push state after the blur event. It's only when users clicked outside the input field that they are happy with their search result. So we only create one or two entries.

Here how it is done:

searchInput.onblur = function(){
    let val = this.value
    if (val !== "") {
        history.pushState({},"Search entry - "+ val,"?q="+encodeURIComponent(val));
    }
}

Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only