Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

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.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>Accessible Autosuggest</h1>


<div id="autocomplete-wrapper">
	<div id="announce" class="visually-hidden" aria-live="assertive"></div>
	<div id="tip" class="visually-hidden">Suggestions will appear below as you type</div>

		<div id="searchfield">
		<form>
			<label for="search">Australian Suburb or Town search</label>
		  <div id="combo_container" role="combobox" aria-owns="res" aria-expanded="false" aria-haspopup="listbox">
				<input id="search" type="text" autocomplete="off"  aria-autocomplete="list" aria-controls="res" aria-describedby="tip">
						
			</div>
				<div id="search-autocomplete"></div>
      <input id="submit" type="submit" value="Search" />
		</form>
		</div>
	
</div>

<!-- Info on required aria role, interactions etc -->
<div class="info">
	<h2>Keyboard Interaction</h2>
	<ul>
		<li><strong>UP and DOWN:</strong> Cycles through auto-suggestions and input field.</li>
		<li><strong>ESC:</strong> Close the menu</li>
		<li><strong>ENTER:</strong> Select the currently focused auto-suggestion and close the menu.</li>
		<li><strong>TAB:</strong> Close the menu, leave what the user has typed in the textbox and move focus to the next focusable element.</li>
	</ul>
	<h2>Screen-reader Interaction</h2>
	<ul>
		<li>when search results are returned the count and instructions are announced.</li>
		<li>when suggestions are arrowed through they are announced.</li>
	</ul>
	<h2>ARIA</h2>
	<ul>
		<li><strong>div:</strong> role="combobox" aria-owns="res" aria-expanded="false" aria-haspopup="listbox"</li>
		<li><strong>input:</strong> aria-autocomplete="list" aria-controls="res" aria-describedby="tip" aria-activedescendant="suggestion-#"</li>
		<li><strong>div:</strong> id="res" role="listbox"</li>
		<li><strong>div:</strong> id="suggestion-#" role="option" aria-selected="false"</li>
	</ul>
	<h2>Notes</h2>
	<ul>
	<li>This code has been updated in line with the<a href="https://www.w3.org/TR/wai-aria-practices/#combobox">ARIA 1.1 combobox design pattern</a></li>
	<li>This is a modified version <a href="https://weboverhauls.github.io/demos/autosuggest/">@dennisl's Accessible Autosuggest Dropdown</a> which was a modification of <a href="http://intopia.digital/articles/anatomy-accessible-auto-suggest/">Intopia's original accessible auto suggest</a></li>
	</ul>
</div>
              
            
!

CSS

              
                #autocomplete-wrapper {
	position: relative;
}

#search-autocomplete {
	position: absolute;
	border: 1px solid #999;
	background: #fff;
	width: 20rem;
	display: none;
}

#res li {
	list-style-type: none;
}

#res li:hover,
#res li.highlight,
#res div:hover,
#res div.highlight {
	background: #110D3B;
	color: #FFF;
}

#search {
	text-transform: capitalize;
	width: 19rem;
}

#searchfield label {
	display: block;
	font-size: 1.35rem;
}

#searchfield form input {
    padding: .5rem;
	border: 2px solid #c8c8c8;
	background-color: #fff;
	border-radius: 6px;
	color: #000;
	font-weight: normal;
	font-size: 1.35em;
	margin: 0 auto;
}

#searchfield form input:focus,
input:focus {
	color: #000;
	border: 2px solid #005499;
}

.autocomplete-suggestion {
	padding: .5rem .25rem;
	font-size: 1.35rem;
	white-space: nowrap;
	overflow: hidden;
}

.autocomplete-selected {
	background: #f0f0f0;
}

div[role=option][aria-selected=true]:after {
	content: " •";
}

.visually-hidden {
	position: absolute !important;
	clip: rect(1px 1px 1px 1px);
}


* {
	font-family: "Arial";
}
.info {
	padding: 1rem;
	margin: 1rem 0;
	border: 1px #ccc solid;
}
div#combo_container {
    display: inline-flex;
}
              
            
!

JS

              
                $(document).ready(function() {
	/*List of suburbs that will act as the list of suggestions for my auto-suggest widget*/
		var resultsLimit = 5;
		var locales = ["Aberfeldy Township", "Altona", "Arthurs Creek", "Arthurs Seat", "Ashwood", "Bacchus Marsh Werribee River", "Ballan", "Beaconsfield Upper", "Beenak", "Berwick", "Blackburn", "Blackburn North", "Blue Mountain", "Box Hill", "Braeside", "Braeside Park", "Broadmeadows", "Brooklyn", "Bulla", "Bulla North", "Bulleen", "Bundoora", "Burnley", "Burwood East", "Cambarville", "Cardinia", "Caulfield", "Caulfield North", "Cement Creek", "Christmas Hills", "Clarkefield", "Clarkefield", "Clayton", "Clearwater Aqueduct", "Coburg", "Coldstream", "Collingwood", "Craigieburn", "Craigieburn East", "Cranbourne", "Dandenong", "Dandenong South", "Dandenong West", "Darraweit", "Deer Park", "Devilbend Reservoir", "Diggers Rest", "Dixons Creek", "Doncaster", "Doncaster East", "Drouin West", "Durdidwarrah", "Eastern G.C. Doncaster", "Elsternwick", "Eltham", "Emerald", "Epping", "Essendon", "Fairfield", "Fawkner", "Fiskville", "Flemington", "Footscray", "Frankston North", "Frankston Pier", "Gardiner", "Glen Forbes South", "Glen Waverley", "Graceburn", "Graceburn Creek Aqueduct", "Greensborough", "Greenvale Reservoir", "Groom's Hill", "Hampton", "Hampton Park", "Hawthorn", "Headworks", "Healesville", "Heathmont", "Heidelberg", "Hurstbridge", "Iona", "Ivanhoe", "Kangaroo Ground", "Keilor", "Keilor North", "Kew", "Keysborough", "Kinglake", "Knox", "Konagaderra", "Kooweerup", "Lake Borrie", "Lancefield", "Lancefield North", "Launching Place", "Lilydale Lake", "Little River", "Loch", "Longwarry North", "Lower Plenty", "Lyndhurst", "Lysterfield", "Maribyrnong", "Maroondah Reservoir", "Melton Reservoir", "Melton Sth Toolern Creek", "Mentone", "Mernda", "Millgrove", "Mitcham", "Montrose", "Mooroolbark", "Mornington", "Mount Dandenong", "Mount Evelyn", "Mount View", "Mt Blackwood", "Mt Bullengarook", "Mt Donna Buang", "Mt Evelyn Stringybark Creek", "Mt Gregory", "Mt Hope", "Mt Horsfall", "Mt Juliet", "Mt Macedon", "Mt St Gwinear", "Mt St Leonard", "Mt Waverley", "Myrrhee", "Narre Warren North", "Nayook", "Neerim South", "Neerim-Elton Rd", "Neerim-Neerim Creek", "Neerim-Tarago East Branch", "Neerim-Tarago West Branch", "North Wharf", "Northcote", "Notting Hill", "Nutfield", "O'Shannassy Reservoir", "Oakleigh South", "Officer", "Officer South", "Olinda", "Pakenham", "Pakenham East", "Pakenham West", "Parwon Parwan Creek", "Poley Tower", "Preston", "Reservoir", "Ringwood", "Rockbank", "Romsey", "Rosslynne Reservoir", "Rowville", "Sandringham", "Scoresby", "Seaford", "Seaford North", "Seville East", "Silvan", "Smiths Gully", "Somerton", "Southbank", "Spotswood", "Springvale", "St Albans", "St Kilda Marina", "Sunbury", "Sunshine", "Surrey Hills", "Tarago Reservoir", "Tarrawarra", "Templestowe", "The Basin", "Thomson Dam", "Tonimbuk", "Toolern Vale", "Torourrong Reservoir", "U/S Goodman Creek Lerderderg River", "Upper Lang Lang", "Upper Pakenham", "Upper Yarra Dam", "Wallaby Creek", "Wallan", "Wantirna South", "Warrandyte", "Williamstown", "Woori Yallock", "Woori Yallock Creek", "Wyndham Vale", "Yallock outflow Cora Lyn", "Yannathan", "Yarra Glen", "Yarra Glen Steels Creek", "Yarra Junction", "Yarra River downstream Doctors Creek", "Yellingbo", "Yering"];
	
	var cache = {};
	var current;
	var searchedBefore = false;
	var counter = 1;
	var highlightCounter = 0;
/*Array of keys used for the keyboard interactions*/
	var keys = {
		ESC: 27,
		TAB: 9,
		RETURN: 13,
		UP: 38,
		DOWN: 40
	};
	$("#search").on("input", function(event) {
		doSearch(locales, resultsLimit);
	});

	$("#search").on("keydown", function(event) {
		doKeypress(keys, event);
	});
});

/*This function performs the search based on the users input, and builds the list of suggestions*/
function doSearch(locales, resultsLimit) {
	var query = $("#search").val();
	$("#search").removeAttr("aria-activedescendant");
	$("#search").removeAttr("aria-controls");

/*If statement to start the search only after 2 characters have been enter. This  number can be higher or lower depending on your preference*/
	if ($("#search").val().length >= 2) {

		//Case insensitive search and return matches to build the  array
		var results = $.grep(locales, function(item) {
			return item.search(RegExp("^" + query, "i")) != -1;
		});

		if (results.length >= 1) {
			/*Start things fresh by removing the suggestions div and emptying the live region before we start*/
			$("#res").remove();
			$('#announce').empty();
			$("#search-autocomplete").show();
			$("#search-autocomplete").append('<div id="res" role="listbox" tabindex="-1"></div>');
			$("#combo_container").attr("aria-expanded","true");
			$("#search").attr("aria-controls","res");
			counter = 1;
		}

		//Bind click event to list elements in results
		$("#res").on("click", "div", function() {
			$("#search").val($(this).text());
			$("#res").remove();
			$('#announce').empty();
			$("#search-autocomplete").hide();
			$("#combo_container").attr("aria-expanded","false");
			$("#search").removeAttr("aria-activedescendant");
			$("#search").removeAttr("aria-controls");
			$('#search').focus();
			counter = 1;
		});

		//Add results to the list
		for (term in results) {
			if (counter <= resultsLimit) {
				$("#res").append("<div role='option' tabindex='-1' class='autocomplete-suggestion' id='suggestion-" + counter + "'>" + results[term] + "</div>");
				counter = counter + 1;
			}
		}
		/*Count the number of suggestions available and annouce to screen readers via live region */
		var number = $("#res").children('[role="option"]').length;
		if (number >= 1) {
			$("#announce").text(number + " suggestions displayed.");
		}
	}
	else {
	/*If no results make sure the list does not display*/
		$("#res").remove();
		$('#announce').empty();
		$("#search-autocomplete").hide();
		$("#combo_container").attr("aria-expanded","false");
		$("#search").removeAttr("aria-controls");
	}
}
/*Function to deal with the keyborad interactions for the auto-suggest and highlight the currently selected option*/
function doKeypress(keys, event) {
	var highlighted = false;
	highlighted = $('#res').children('div').hasClass('highlight');
	switch (event.which) {

		case keys.ESC:
			$("#search").removeAttr("aria-activedescendant");
			$("#res").remove();
			$('#announce').empty();
			$("#search-autocomplete").hide();
			$("#combo_container").attr("aria-expanded","false");
			$("#search").removeAttr("aria-controls");
			break;

		case keys.TAB:
			$("#search").removeAttr("aria-activedescendant");
			$("#res").remove();
			$('#announce').empty();
			$("#search-autocomplete").hide();
			$("#combo_container").attr("aria-expanded","false");
			$("#search").removeAttr("aria-controls");
			break;

		case keys.RETURN:
			if (highlighted) {
				event.preventDefault();
				event.stopPropagation();
				return selectOption(highlighted);
			}

		case keys.UP:
			event.preventDefault();
			event.stopPropagation();
			return moveUp(highlighted);
			break;

		case keys.DOWN:
			event.preventDefault();
			event.stopPropagation();
			return moveDown(highlighted);
			break;

		default:
			return;
	}
}

/*Function to move the user up the list of suggestions*/
function moveUp(highlighted) {
	$("#search").removeAttr("aria-activedescendant");

	// if highlighted exists and if the highlighted item is not the first option
	if (highlighted && !$("#res").children().first('div').hasClass('highlight')) {
		removeCurrent();
		current.prev('div').addClass('highlight').attr('aria-selected', true);
		$("#search").attr("aria-activedescendant", current.prev('div').attr('id'));
	}
	else {
		// Go to bottom of list
		removeCurrent();
		current = $("#res").children().last('div');
		current.addClass('highlight').attr('aria-selected', true);
		$("#search").attr("aria-activedescendant", current.attr('id'));
	}
}
/*Function to move the user down the list of suggestions*/
function moveDown(highlighted) {
	$("#search").removeAttr("aria-activedescendant");

	// if highlighted exists and if the highlighted item is not the last option
	if (highlighted && !$("#res").children().last('div').hasClass('highlight')) {
		removeCurrent();
		current.next('div').addClass('highlight').attr('aria-selected', true);
		$("#search").attr("aria-activedescendant", current.next('div').attr('id'));
	}
	else {
		// Go to top of list
		removeCurrent();
		current = $("#res").children().first('div');
		current.addClass('highlight').attr('aria-selected', true);
		$("#search").attr("aria-activedescendant", current.attr('id'));
	}
}

function removeCurrent() {
	current = $('#res .highlight');
	current.attr('aria-selected', false);
	current.removeClass('highlight');	
}

/*Function to select the users chosen option*/
function selectOption(highlighted) {
	if (highlighted) {
		$("#search").removeAttr("aria-activedescendant");
		$('#search').val($('.highlight').text());
		$('#search').focus();
		$("#res").remove();
		$('#announce').empty();
		$("#search-autocomplete").hide();
		$("#combo_container").attr("aria-expanded","false");
		$("#search").removeAttr("aria-controls");
	}
	else {
		return;
	}
}
              
            
!
999px

Console