HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<h1>Address autocomplete demo using Postcoder</h1>
<form>
<fieldset>
<label for="apikey">API key | Not got one? <a href="https://postcoder.com/sign-up" target="_blank">Start a free Postcoder trial</a></label>
<input type="text" id="apikey" />
<label for="txt_country" class="bold">Country</label>
<select id="txt_country">
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
<option value="AS">American Samoa</option>
<option value="AD">Andorra</option>
<option value="AO">Angola</option>
<option value="AI">Anguilla</option>
<option value="AQ">Antarctica</option>
<option value="AG">Antigua and Barbuda</option>
<option value="AR">Argentina</option>
<option value="AM">Armenia</option>
<option value="AW">Aruba</option>
<option value="AU">Australia</option>
<option value="AT">Austria</option>
<option value="AZ">Azerbaijan</option>
<option value="BS">Bahamas</option>
<option value="BH">Bahrain</option>
<option value="BD">Bangladesh</option>
<option value="BB">Barbados</option>
<option value="BY">Belarus</option>
<option value="BE">Belgium</option>
<option value="BZ">Belize</option>
<option value="BJ">Benin</option>
<option value="BM">Bermuda</option>
<option value="BT">Bhutan</option>
<option value="BO">Bolivia</option>
<option value="BQ">Bonaire, Sint Eustatius And Saba</option>
<option value="BA">Bosnia and Herzegovina</option>
<option value="BW">Botswana</option>
<option value="BV">Bouvet Island</option>
<option value="IO">Br. Indian Ocean Ter.</option>
<option value="BR">Brazil</option>
<option value="BN">Brunei Darussalam</option>
<option value="BG">Bulgaria</option>
<option value="BF">Burkina Faso</option>
<option value="BI">Burundi</option>
<option value="KH">Cambodia</option>
<option value="CM">Cameroon</option>
<option value="CA">Canada</option>
<option value="CV">Cape Verde</option>
<option value="KY">Cayman Islands</option>
<option value="CF">Central African Rep.</option>
<option value="TD">Chad</option>
<option value="CL">Chile</option>
<option value="CN">China</option>
<option value="CX">Christmas Island</option>
<option value="CC">Cocos (Keeling) Islands</option>
<option value="CO">Colombia</option>
<option value="KM">Comoros</option>
<option value="CD">Congo (Dem. Rep.)</option>
<option value="CG">Congo (Rep.)</option>
<option value="CK">Cook Islands</option>
<option value="CR">Costa Rica</option>
<option value="CI">Côte d'Ivoire</option>
<option value="HR">Croatia</option>
<option value="CU">Cuba</option>
<option value="CW">Curacao</option>
<option value="CY">Cyprus</option>
<option value="CZ">Czech Republic</option>
<option value="DK">Denmark</option>
<option value="DJ">Djibouti</option>
<option value="DM">Dominica</option>
<option value="DO">Dominican Republic</option>
<option value="EC">Ecuador</option>
<option value="EG">Egypt</option>
<option value="SV">El Salvador</option>
<option value="GQ">Equatorial Guinea</option>
<option value="ER">Eritrea</option>
<option value="EE">Estonia</option>
<option value="ET">Ethiopia</option>
<option value="FK">Falkland Is. (Malvinas)</option>
<option value="FO">Faröe Islands</option>
<option value="FJ">Fiji</option>
<option value="FI">Finland</option>
<option value="FR">France</option>
<option value="GF">French Guiana</option>
<option value="PF">French Polynesia</option>
<option value="TF">French Southern Territories</option>
<option value="GA">Gabon</option>
<option value="GM">Gambia</option>
<option value="GE">Georgia</option>
<option value="DE">Germany</option>
<option value="GH">Ghana</option>
<option value="GI">Gibraltar</option>
<option value="GR">Greece</option>
<option value="GL">Greenland</option>
<option value="GD">Grenada</option>
<option value="GP">Guadeloupe</option>
<option value="GU">Guam</option>
<option value="GT">Guatemala</option>
<option value="GG">Guernsey</option>
<option value="GN">Guinea</option>
<option value="GW">Guinea-Bissau</option>
<option value="GY">Guyana</option>
<option value="HT">Haiti</option>
<option value="HM">Heard Island and McDonald Islands</option>
<option value="HN">Honduras</option>
<option value="HK">Hong Kong</option>
<option value="HU">Hungary</option>
<option value="IS">Iceland</option>
<option value="IN">India</option>
<option value="ID">Indonesia</option>
<option value="IR">Iran</option>
<option value="IQ">Iraq</option>
<option value="IE">Ireland</option>
<option value="IM">Isle of Man</option>
<option value="IL">Israel</option>
<option value="IT">Italy</option>
<option value="JM">Jamaica</option>
<option value="JP">Japan</option>
<option value="JE">Jersey</option>
<option value="JO">Jordan</option>
<option value="KZ">Kazakhstan</option>
<option value="KE">Kenya</option>
<option value="KI">Kiribati</option>
<option value="KP">Korea (Dem. Rep.)</option>
<option value="KR">Korea (Rep.)</option>
<option value="KW">Kuwait</option>
<option value="KG">Kyrgyzstan</option>
<option value="LA">Laos</option>
<option value="LV">Latvia</option>
<option value="LB">Lebanon</option>
<option value="LS">Lesotho</option>
<option value="LR">Liberia</option>
<option value="LY">Libya</option>
<option value="LI">Liechtenstein</option>
<option value="LT">Lithuania</option>
<option value="LU">Luxembourg</option>
<option value="MO">Macao</option>
<option value="MK">Macedonia, TFYR</option>
<option value="MG">Madagascar</option>
<option value="MW">Malawi</option>
<option value="MY">Malaysia</option>
<option value="MV">Maldives</option>
<option value="ML">Mali</option>
<option value="MT">Malta</option>
<option value="MH">Marshall Islands</option>
<option value="MQ">Martinique</option>
<option value="MR">Mauritania</option>
<option value="MU">Mauritius</option>
<option value="YT">Mayotte</option>
<option value="MX">Mexico</option>
<option value="FM">Micronesia</option>
<option value="MD">Moldova</option>
<option value="MC">Monaco</option>
<option value="MN">Mongolia</option>
<option value="ME">Montenegro</option>
<option value="MS">Montserrat</option>
<option value="MA">Morocco</option>
<option value="MZ">Mozambique</option>
<option value="MM">Myanmar</option>
<option value="NA">Namibia</option>
<option value="NR">Nauru</option>
<option value="NP">Nepal</option>
<option value="NL">Netherlands</option>
<option value="NC">New Caledonia</option>
<option value="NZ">New Zealand</option>
<option value="NI">Nicaragua</option>
<option value="NE">Niger</option>
<option value="NG">Nigeria</option>
<option value="NU">Niue</option>
<option value="NF">Norfolk Island</option>
<option value="MP">Northern Mariana Islands</option>
<option value="NO">Norway</option>
<option value="OM">Oman</option>
<option value="PK">Pakistan</option>
<option value="PW">Palau</option>
<option value="PS">Palestinian Territory</option>
<option value="PA">Panama</option>
<option value="PG">Papua New Guinea</option>
<option value="PY">Paraguay</option>
<option value="PE">Peru</option>
<option value="PH">Philippines</option>
<option value="PN">Pitcairn</option>
<option value="PL">Poland</option>
<option value="PT">Portugal</option>
<option value="PR">Puerto Rico</option>
<option value="QA">Qatar</option>
<option value="RE">Réunion</option>
<option value="RO">Romania</option>
<option value="RU">Russia</option>
<option value="RW">Rwanda</option>
<option value="GS">S. Georgia and S. Sandwich</option>
<option value="SH">Saint Helena</option>
<option value="LC">Saint Lucia</option>
<option value="MF">Saint Martin</option>
<option value="PM">Saint Pierre and Miquelon</option>
<option value="BL">Saint-Barthélemy</option>
<option value="WS">Samoa</option>
<option value="SM">San Marino</option>
<option value="ST">Sao Tomé and Principe</option>
<option value="SA">Saudi Arabia</option>
<option value="SN">Senegal</option>
<option value="RS">Serbia</option>
<option value="SC">Seychelles</option>
<option value="SL">Sierra Leone</option>
<option value="SG">Singapore</option>
<option value="SX">Sint Maarten</option>
<option value="SK">Slovakia</option>
<option value="SI">Slovenia</option>
<option value="SB">Solomon Islands</option>
<option value="SO">Somalia</option>
<option value="ZA">South Africa</option>
<option value="SS">South Sudan</option>
<option value="ES">Spain</option>
<option value="LK">Sri Lanka</option>
<option value="KN">St. Kitts and Nevis</option>
<option value="VC">St. Vincent and Grenadines</option>
<option value="SD">Sudan</option>
<option value="SR">Suriname</option>
<option value="SJ">Svalbard and Jan Mayen</option>
<option value="SZ">Swaziland</option>
<option value="SE">Sweden</option>
<option value="CH">Switzerland</option>
<option value="SY">Syria</option>
<option value="TW">Taiwan</option>
<option value="TJ">Tajikistan</option>
<option value="TZ">Tanzania</option>
<option value="TH">Thailand</option>
<option value="TL">Timor-Leste</option>
<option value="TG">Togo</option>
<option value="TK">Tokelau</option>
<option value="TO">Tonga</option>
<option value="TT">Trinidad and Tobago</option>
<option value="TN">Tunisia</option>
<option value="TR">Turkey</option>
<option value="TM">Turkmenistan</option>
<option value="TC">Turks and Caicos Is.</option>
<option value="TV">Tuvalu</option>
<option value="UG">Uganda</option>
<option value="UA">Ukraine</option>
<option value="AE">United Arab Emirates</option>
<option value="UK" selected>United Kingdom</option>
<option value="UM">United States Minor Outlying Islands</option>
<option value="US">United States of America</option>
<option value="VI">United States Virgin Islands</option>
<option value="UY">Uruguay</option>
<option value="UZ">Uzbekistan</option>
<option value="VU">Vanuatu</option>
<option value="VA">Vatican City</option>
<option value="VE">Venezuela</option>
<option value="VN">Viet Nam</option>
<option value="VG">Virgin Islands, British</option>
<option value="WF">Wallis and Futuna</option>
<option value="EH">Western Sahara</option>
<option value="YE">Yemen</option>
<option value="ZM">Zambia</option>
<option value="ZW">Zimbabwe</option>
</select>
<div class="autocomplete_wrap">
<label for="txt_search" class="bold">
Start typing your address or postcode
</label>
<input id="txt_search" />
<ul id="suggestion_list"></ul>
</div>
</fieldset>
<label for="txt_organisation">Organisation</label>
<input type="text" id="txt_organisation" />
<label for="txt_addressline1">Address</label>
<input type="text" id="txt_addressline1" />
<input type="text" id="txt_addressline2" />
<input type="text" id="txt_addressline3" />
<label for="txt_posttown">Town</label>
<input type="text" id="txt_posttown" />
<label for="txt_postcode">Postcode</label>
<input type="text" id="txt_postcode" />
</form>
<p>Download the <a href="https://postcoder.com/docs/sample-code/address-lookup" target="_blank">full code example</a> or explore the <a href="https://postcoder.com/docs/address-lookup/autocomplete-find" target="_blank">API reference</a> by <a href="https://postcoder.com" target="_blank">Postcoder</a>.</p>
/* Heading style */
h1 {
font-size: 1.17rem;
}
/* Fieldset for address search inputs */
fieldset {
background-color: #e5e5e5;
border: none;
border-radius: 0.5rem;
margin: 0;
}
/* Form labels */
label {
display: block;
margin-block: 1.25rem 0.25rem;
}
/* General form inputs */
input,
select {
display: block;
box-sizing: border-box;
width: 100%;
padding: 10px;
height: 40px;
margin-block-end: 0.5rem;
border: solid lightgray 1px;
}
/* Default button styles */
button {
padding: 0.5rem 1rem;
border: none;
background-color: #292929;
color: #fff;
font-family: sans-serif;
font-weight: bold;
}
/* Wrapper for Autocomplete search input */
#autocomplete_wrap {
position: relative;
}
/* Dropdown list for returned search terms */
#suggestion_list {
position: absolute;
background-color: #fff;
outline: -webkit-focus-ring-color auto 1px;
list-style-type: none;
margin: 0;
padding: 0;
max-height: 400px;
overflow-y: auto;
}
#suggestion_list li {
cursor: pointer;
padding: 0.5rem 1rem;
}
#suggestion_list li.header {
border-bottom: 2px solid #ddd;
}
#suggestion_list li:hover,
#suggestion_list li.selected {
background-color: #ddd;
}
#suggestion_list li span.extra-info {
font-size: 0.75em;
color: #666;
}
/* Back arrow that appears in drop down list */
.arrow {
border: solid black;
border-width: 0 3px 3px 0;
display: inline-block;
padding: 3px;
}
.arrow.left {
margin-left: 3px;
transform: rotate(135deg);
-webkit-transform: rotate(135deg);
}
/* Set the body tag defaults */
body {
font-family: sans-serif;
}
class PostcoderAutocomplete {
constructor(config) {
this.config = config;
this.init();
}
init = () => {
this.suggestionendpoint = "https://ws.postcoder.com/pcw/autocomplete/find";
this.retrieveendpoint =
"https://ws.postcoder.com/pcw/autocomplete/retrieve";
this.cache = [];
this.suggestionhierarchy = [];
this.suggestions = [];
this.searchterm = "";
this.selectedoptiontext = "";
this.pathfilter = "";
this.selectedIndex = -1;
this.no_results_message = "No addresses found";
this.inputdelay = 300;
this.singlesummary = this.config.singlesummary;
this.abortController = null;
this.suggestionlist = document.querySelector(this.config.suggestions);
this.input = document.querySelector(this.config.searchterm);
this.apiKeyInput = document.querySelector(this.config.apikey);
this.input.setAttribute("type", "search");
this.input.setAttribute("autocomplete", "off");
this.input.setAttribute("autocapitalize", "off");
this.input.setAttribute("autocorrect", "off");
this.input.setAttribute("spellcheck", "false");
this.input.addEventListener("input", this.handleInput);
this.input.addEventListener("focus", this.handleFocus);
this.input.addEventListener("keydown", this.handleKeyDown);
this.apiKeyInput.addEventListener("input", this.handleApiKeyInputChange);
this.suggestionlist.addEventListener("click", this.handleSuggestionClick);
// Add click event listener to the document, to hide the suggestions when clicked away
document.body.addEventListener("click", this.handleDocumentClick);
// Determine the number of addresslines required
this.addresslines = 0;
for (let i = 1; i <= 4; i++) {
if (this.config["addressline" + i] !== "") {
this.addresslines++;
}
}
};
getSuggestions = (event) => {
this.searchterm = encodeURIComponent(this.input.value.trim());
// Require a minimum of three characters
if (this.searchterm.length < 3) {
this.hideSuggestions();
return;
}
let url =
this.suggestionendpoint +
"?apikey=" +
this.apikey +
"&country=" +
this.getCountry() +
"&maximumresults=10" +
"&query=" +
this.searchterm;
if (this.pathfilter) {
url += "&pathfilter=" + encodeURIComponent(this.pathfilter);
} else {
this.selectedoptiontext = this.searchterm;
}
if (this.singlesummary) {
url += "&singlesummary=true";
}
let index = this.cache.findIndex((c) => c.url === url);
if (index >= 0) {
// Use cached data
this.suggestions = this.cache[index].suggestions;
this.addSuggestionHierarchy(index);
this.showSuggestions();
} else {
this.abortController = new AbortController();
fetch(url, { signal: this.abortController.signal })
.then((response) => {
if (!response.ok) {
throw response;
}
return response.json();
})
.then((json) => {
this.suggestions = json;
this.addCache(url);
this.addSuggestionHierarchy(this.cache.length - 1);
this.showSuggestions();
})
.catch((err) => {
if (typeof err.text === "function") {
err.text().then((errorMessage) => {
console.log(
"Postcoder request error " + err.status + " : " + errorMessage
);
});
} else {
console.log(err);
}
});
}
};
preselectCountry = () => {
// Use Postcoder's ipaddress endpoint to pre-select the country list
if (this.config.geolocate) {
fetch("https://ws.postcoder.com/pcw/" + this.apikey + "/ipaddress")
.then((response) => {
if (!response.ok) {
throw response;
}
return response.json();
})
.then((json) => {
// Make our selection
document.querySelector(this.config.country).value = json.countrycode;
})
.catch((err) => {
if (typeof err.text === "function") {
err.text().then((errorMessage) => {
console.error(
"Postcoder ipaddress endpoint request error " +
err.status +
" : " +
errorMessage
);
});
} else {
console.log(err);
}
});
}
};
addCache = (url) => {
let obj = {};
obj.url = url;
obj.suggestions = this.suggestions;
obj.label = this.selectedoptiontext;
this.cache.push(obj);
};
newSuggestionsReset = () => {
// Remove previous options
this.hideSuggestions();
this.pathfilter = "";
this.suggestionlist.scrollTop = 0;
this.selectedIndex = -1;
};
suggestionsHierarchyReset = () => {
// Reset suggestionHierarchy
this.suggestionhierarchy = [];
};
addSuggestionHierarchy = (index) => {
// Store the cache entry index for each suggestion level selected
this.suggestionhierarchy.push(index);
};
handleSuggestionClick = (event) => {
event.stopPropagation();
let target = event.target;
// If click was not directly on the <li>, but a child, find the <li> in parent
while (target.tagName.toLowerCase() !== "li") {
target = target.parentNode;
}
this.selectSuggestion(target);
};
selectSuggestion = (target) => {
this.selectedoptiontext = target.innerHTML;
if (target.getAttribute("data-type") == "CACHE") {
// Back to previous results using cached suggestions
this.suggestions = this.cache[target.getAttribute("data-id")].suggestions;
this.suggestionhierarchy.pop();
this.showSuggestions();
} else if (target.getAttribute("data-type") == "ADD") {
// If the type is an address, retrieve it using the id
this.retrieve(target.getAttribute("data-id"));
} else {
// Get more suggestions, using the id
this.pathfilter = target.getAttribute("data-id");
this.getSuggestions();
}
};
retrieve = (id) => {
const country = this.getCountry();
const url =
this.retrieveendpoint +
"?apikey=" +
this.apikey +
"&country=" +
country +
"&query=" +
this.searchterm +
"&id=" +
id +
"&lines=" +
this.addresslines +
"&exclude=" +
"organisation,posttown,county,postcode,country";
// Fetch the json formatted result from Postcoder and pass it to processResult
fetch(url)
.then((response) => {
if (!response.ok) {
throw response;
}
return response.json();
})
.then((addresses) => {
// Always one result, use the first array item
this.cache[url] = addresses[0];
this.processResult(addresses[0]);
})
.catch((err) => {
if (typeof err.text === "function") {
err.text().then((errorMessage) => {
console.log(
"Postcoder request error " + err.status + " : " + errorMessage
);
});
} else {
console.log(err);
}
});
};
showSuggestions = () => {
this.newSuggestionsReset();
if (this.suggestions.length === 0) {
// Show no results message in ul
let option = document.createElement("li");
option.innerHTML = this.no_results_message;
this.suggestionlist.appendChild(option);
} else {
if (this.suggestionhierarchy.length > 1) {
// A suggestion was selected so show previous option
let cacheid = this.suggestionhierarchy[
this.suggestionhierarchy.length - 2
]; // .length -1 is current suggestions
let option = document.createElement("li");
option.classList.add("header");
option.innerHTML =
'<i class="arrow left"></i> ' +
decodeURIComponent(this.cache[cacheid].label);
option.setAttribute("data-id", cacheid);
option.setAttribute("data-type", "CACHE");
this.suggestionlist.appendChild(option);
}
for (let i = 0; i < this.suggestions.length; i++) {
let option = document.createElement("li");
let suggestiontext = "";
if (this.singlesummary) {
suggestiontext = this.suggestions[i].summaryline;
} else {
suggestiontext =
this.suggestions[i].summaryline +
" " +
'<span class="extra-info">' +
this.suggestions[i].locationsummary +
"</span>";
}
if (this.suggestions[i].count > 1) {
let count =
this.suggestions[i].count > 100
? "100+"
: this.suggestions[i].count;
if (this.singlesummary) {
suggestiontext +=
' <span class="extra-info">(' + count + " addresses)</span>";
} else {
suggestiontext += " (" + count + " addresses)";
}
}
option.innerHTML = suggestiontext;
// Add the id and type attibutes to the option
option.setAttribute("data-id", this.suggestions[i].id);
option.setAttribute("data-type", this.suggestions[i].type);
this.suggestionlist.appendChild(option);
}
}
};
getCountry = () => {
// If the countrycode is provided via config object, use that.
// If not, use html input
return typeof this.config.countrycode !== "undefined" &&
this.config.countrycode !== ""
? this.config.countrycode
: document.querySelector(this.config.country).value;
};
updateApiKey = () => {
this.apikey = this.apiKeyInput.value;
this.preselectCountry();
};
handleApiKeyInputChange = () => {
this.updateApiKey();
};
processResult = (address) => {
this.hideSuggestions();
let fields = [
"organisation",
"addressline1",
"addressline2",
"addressline3",
"addressline4",
"posttown",
"county",
"postcode"
];
// Populate the address form
for (let i = 0; i < fields.length; i++) {
let field_selector = this.config[fields[i]];
if (typeof field_selector !== "undefined" && field_selector !== "") {
document.querySelector(field_selector).value =
typeof address[fields[i]] !== "undefined" ? address[fields[i]] : "";
}
}
};
handleDocumentClick = (event) => {
if (
this.suggestionlist.contains(event.target) ||
this.input.contains(event.target)
) {
return;
}
this.hideSuggestions();
};
hideSuggestions = () => {
// Clear the ul list
this.suggestionlist.innerHTML = "";
};
handleKeyDown = (event) => {
const { key } = event;
switch (key) {
case "Up":
case "Down":
case "ArrowUp":
case "ArrowDown": {
const selectedIndex =
key === "ArrowUp" || key === "Up"
? this.selectedIndex - 1
: this.selectedIndex + 1;
event.preventDefault();
this.handleArrows(selectedIndex);
break;
}
case "Tab": {
this.handleTab(event);
break;
}
case "Enter": {
this.selectSuggestion(
this.suggestionlist.querySelectorAll("li")[this.selectedIndex]
);
break;
}
case "Esc":
case "Escape": {
this.hideSuggestions();
this.setValue();
break;
}
default:
return;
}
};
handleArrows = (selectedIndex) => {
// Loop selectedIndex back to first or last result if out of bounds
let suggestionsCount = this.suggestions.length;
if (this.suggestionhierarchy.length > 1) {
// Add previous suggestion
suggestionsCount++;
}
if (this.suggestionlist.querySelectorAll("li").length > 0) {
if (this.selectedIndex >= 0) {
// Clear the previously selected class
this.suggestionlist
.querySelectorAll("li")
[this.selectedIndex].classList.remove("selected");
}
this.selectedIndex =
((selectedIndex % suggestionsCount) + suggestionsCount) %
suggestionsCount;
// Set the selected class
this.suggestionlist
.querySelectorAll("li")
[this.selectedIndex].classList.add("selected");
// Scroll into view
this.suggestionlist
.querySelectorAll("li")
[this.selectedIndex].scrollIntoView(false);
}
};
handleTab = (event) => {
if (this.selectedIndex >= 0) {
event.preventDefault();
this.selectSuggestion(
this.suggestionlist.querySelectorAll("li")[this.selectedIndex]
);
} else {
this.hideSuggestions();
}
};
handleInput = () => {
this.suggestionsHierarchyReset();
clearTimeout(this.debounce);
if (this.abortController !== null) {
this.abortController.abort("New input detected.");
}
this.debounce = setTimeout(() => this.getSuggestions(), this.inputdelay);
};
handleFocus = () => {
if (this.suggestions.length > 0) {
this.showSuggestions();
} else {
this.getSuggestions();
}
};
}
new PostcoderAutocomplete({
apikey: "#apikey", // Query selector of the API key input field
geolocate: false, // Automatically pre-select the country select list based on user's IP address; additional credit cost, see https://postcoder.com/docs/address-lookup/ipaddress
searchterm: "#txt_search", // Query selector of the searchterm input field
singlesummary: true, // Boolean; true to show one summary line for each suggestion, false to show two parts which can be styled independently
suggestions: "#suggestion_list", // Query selector for preview datalist
country: "#txt_country", // Country select list; leave blank if not using a country select list
countrycode: "", // Hard code if not using a country select list; leave blank otherwise
organisation: "#txt_organisation", // Leave blank if form does not have a separate organisation field
addressline1: "#txt_addressline1",
addressline2: "#txt_addressline2", // Leave blank if form does not have an addressline2
addressline3: "#txt_addressline3", // Leave blank if form does not have an addressline3
addressline4: "", // Leave blank if form does not have an addressline4
county: "", // Leave blank if form does not have a county
posttown: "#txt_posttown",
postcode: "#txt_postcode"
});
Also see: Tab Triggers