Options
All
  • Public
  • Public/Protected
  • All
Menu

@ideal-postcodes/address-finder

Ideal Postcodes Address Finder JavaScript Library

Find and autocomplete addresses with Address Finder

codecov npm version npm bundle size (scoped)

@ideal-postcodes/address-finder is a JavaScript library that delivers address autocomplete (or address typeahead) search functionality on a webpage.

This package should be consumed by a bundler or transpiler (e.g. webpack, parcel, rollup) for minification, module resolution and specific browser support.

For a pre-bundled version of address-finder (minified, transpiled, polyfilled, etc) that can immediately be dropped on a webpage, use address-finder-bundled.

Address Finder Demo

Links

Example Setup

Webpack Demo

Parcel Demo

Rollup Demo

React Demo

Related Projects

How it Works

  1. Add the library to your project. Your webpage should have pre-existing address input fields as well as an input field to host the finder
  2. Run initialisation code providing a reference to the Address Finder input and any other configuration
  3. When initialising, Address Finder will perform a key check to determine whether it is usable. If the check fails, initialisation is aborted. Use the onCheckFailed callback to update your page for manual address entry.
  4. When initialised, Address Finder binds to the input field of your choice and renders a dropdown of address suggestion when the user starts typing

Documentation

Configuration & Usage

Install

Add address-finder to your project via npm

npm install @ideal-postcodes/address-finder

Instantiate

Instantiate Address Finder with AddressFinder.setup.

import { AddressFinder } from "@ideal-postcodes/address-finder";

const controller = AddressFinder.setup({
  inputField: "#line_1", // Target <input> to host Address Finder
  apiKey: "iddqd", // API Key from your account
  outputFields: {
    // Target address fields
    line_1: "#line_1",
    line_2: "#line_2",
    line_3: "#line_3",
    post_town: "#post_town",
    postcode: "#postcode",
  },
});

Configuration options

It's also possible to pass HTMLElements as inputField or outputFields.

AddressFinder.setup({
  inputField: document.getElementById("line_1"),
  outputFields: {
    line_1: document.getElementById("line_1"),
  },
  apiKey: "iddqd",
});

Detach

After instantiating Address Finder, it is possible to toggle availability with the .detach() and .attach() methods.

// Removes Address Finder from DOM and clears event listeners
controller.view.detach();

// Restores Address Finder to the DOM and start event listeners
controller.view.attach();

Quickstart

A complete list of quick integration examples can be found at ideal-postcodes.co.uk/address-finder-demo

Populating your Address Fields

Address Finder expects you to address inputs on the page ready to be populated.

When an address is select, the addressing data will be piped to those address inputs designated in outputFields. For instance line_1: "#line_1" will write Address Line One data to a HTML entity with ID line_1.

Assigning the 3 address line, post town and postcode fields, is all addressing information required to identify a UK premise. You may extract more data for an address by passing more properties into the outputFields configuration object.

The configuration attributes for outputFields matches the Address response object. E.g. street name can be populated can be populated using the thoroughfare attribute. A list of address attributes provided by the API can be found at @ideal-postcodes/api-typings.

More information on addressing data can be found on our data documentation.

For more sophistated behaviour when a user selects an address, you can hook into the onAddressRetrieved callback and implement customised behaviour there.

Styling

The Address Finder's default CSS stylesheet can be found in the css/ directory of this repository.

The Address Finder view CSS is structured in the following way:

  • The target input and Address Finder suggestion list is wrapped in a <div> with a default class of idpc_autocomplete
  • Address Suggestions are rendered in a <ul> list with a default class of idpc_ul
  • Any messages (including prompts to type, errors, etc) are rendered in a <li> with a default class of idpc_error

You can override default CSS classes. For instance, containerClass, listClass and messageClass are all defined in defaults.

injectStyle

Set injectStyle: false to prevent default Address Finder styles from being added to DOM. Defaults to true.

Set to a URL to retrieve a CSS stylesheet. E.g.

{
  injectStyle: "https://cdn.jsdelivr.net/npm/@ideal-postcodes/address-finder@1.2.1/css/address-finder.min.css",
}

Messages

Default messages (e.g. "Start typing to find address", "No matches found") can be overridden. See:

Setup Options

AddressFinder.setup() accepts a single configuration object and returns the Address Finder controller instance.

Below is the list of parameters you can use to modify Address Finder.

A complete list of configuration options can be found in the library documentation

Required Config

apiKey

API Key from your Ideal Postcodes account. Typically begins ak_

outputFields

Specify where to send address data given a selected address. A object which maps an address attribute to the CSS selector of an input field or HTMLElement like HTMLInputElement or HTMLTextAreaElement.

{
  line_1: "#line_1",
  line_2: "#line_2",
  line_3: "input[name='line_3']",
  post_town: document.getElementById("post_town"),
  postcode: document.getElementById("postcode")
}

The configuration attributes for outputFields matches the Address response object. E.g. street name can be populated can be populated using the thoroughfare attribute. A list of address attributes provided by the API can be found at @ideal-postcodes/api-typings.

More complex, dynamic assignment can be performed using the onAddressRetrieved callback.

Output fields assigned with a query selector are evaluated lazily (i.e. when an address attribute needs to be piped to a field).

Configure Behaviour

inputField

Configure inputField if you want Address Finder to render on an input field which is not your first address line.

CSS selector or HTML Element which specifies the <input> field which the Address Finder interface should bind.

Defaults to outputFields.line_1 (the first address line).

checkKey

If enabled, the plugin will check if the key is in a usable state before initialising itself.

Defaults to true.

The check can fail if:

  • Your key has no remaining lookups
  • Your key has run into its lookup limit for the day
  • Your key is requested from a URL which is not on your whitelist
  • The user seeking to use the key has exceeded their limit for the day

If the check fails, the plugin will not initialise. You can use the onFailedCheck callback to customise your response to a failed check.

titleizePostTown

An optional field to convert the case of the Post Town from upper case into title case. E.g. "LONDON" becomes "London".

Defaults to true.

removeOrganisation

If set to true, organisation name will be removed from the address.

Defaults to false.

autocomplete

Sets the autocomplete= attribute of the input element. Setting this attribute aims to prevent some browsers (particularly Chrome) from providing a clashing autofill overlay.

The best practice for this attribute breaks over time (see https://stackoverflow.com/questions/15738259/disabling-chrome-autofill) and is specific to different forms. If you are observing Chrome's autofill clashing on your form, update this attribute to the best practice du jour.

Defaults to "none".

hide

Accepts an array of HTMLElements or CSS selectors. E.g.

{
  hide: [
    "#line_1",
    document.getElementById("line_2"),
    document.getElemmentById("line_3")],
  ],
}

When enabled, the HTMLElements supplied in hide are hidden with display: none; when Address Finder initialises and attaches to the DOM. These elements will be subsequently unhidden if an address is selected or the user opts to manually input an address.

Enabling this feature will also create a clickable element in the Address Finder, which provides users the option to manually input an address. You may provide your own clickable element with unhide or customise the clickable element with msgUnhide and unhideClass.

Defaults to [].

unhide

Specify a query selector (string) or (HTMLElement) as a custom clickable element to unhide and form fields configured with hide. This will prevent the default unhide element from being rendered.

Lifecycle Callbacks

Address Finder also provides callbacks which let you hook into specific events in the controller lifecyle.

onLoaded

Invoked when Address Finder has been successfully attached to the input element.

onFailedCheck

A function invoked if checkKey is enabled and the check fails.

onSuggestionsRetrieved

Invoked immediately after address suggestions are retrieved from the API. The first argument is an array of address suggestions.

onAddressSelected

Invoked immediately after the user has selected a suggestion (either by click or keypress). The first argument is an object which represents the suggestion selected.

onAddressRetrieved

Invoked when the Address Finder client has retrieved a full address from the API following a user accepting a suggestion. The first argument is an object representing the address that has been retrieved.

onSearchError

Invoked when an error has occurred following an attempt to retrieve a full address. In this scenario the user will also receive a message to manually input their address.

The first argument is an error instance (i.e. inherits from Error) representing the error which has occurred.

Examples of errors includes "lookup balance exhausted" and "lookup limit reached" errors.

onSuggestionError

Invoked when an error has occurred following an attempt to retrieve suggestions for a key press. In this scenario the user will also receive a message to manually input their address.

The first argument is an error instance (i.e. inherits from Error) representing the error which has occurred.

Examples of errors includes "lookup balance exhausted" and "lookup limit reached" errors.

onOpen

Invoked when Address Finder suggestion box is opened (i.e. presented to the user).

onBlur

Invoked when the user unfocuses from the address input field.

onClose

Invoked when Address Finder suggestion box is closed (i.e. hidden from user).

onFocus

Invoked when user selects or focuses address input field.

onInput

Invoked when user selects or focuses address input field.

onMounted

Invoked when controller attaches to the DOM (controller.view.attach()).

onRemove

Invoked when controller detaches from the DOM (controller.view.detach()).

onAddressPopulated

Invoked after the selected address is applied to input fields.

Licence

Copyright © IDDQD Limited