Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

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.

+ add another resource

JavaScript

Babel includes JSX processing.

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

Packages

Add Packages

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.

Behavior

Auto Save

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 auto-suggest</h1>

<!-- A live region to announce number of suggestions presented-->
<div id='announce' class='visually-hidden' aria-live="assertive"></div>

<div id="searchfield">
	<form>
		<label for="search">Suburb or Town Search</label>
		<!-- Search field. aria-autocomplete is 'both' -->		
		<input role="combobox" id="search" type="text" class="biginput" autocomplete="off" aria-owns="res" aria-autocomplete="both">

	</form>
</div>
<!-- Container for the suggestions div. this is used for styling purposes, it's the div that sits inside this that actually counts -->
<div class="autocomplete-suggestions" id="search-autocomplete"></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>input:</strong> role="combobox" aria-owns="search-autocomplete" aria-autocomplete="both" 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>

</div>
              
            
!

CSS

              
                * {
	font-family: "Arial";
}

#res {
	margin: 0px;
	padding-left: 0px;
}

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

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

#searchfield {
	display: block;
	width: 100%;
	text-align: center;
	margin-bottom: 5px;
}

#searchfield form {
	display: inline-block;
	background: #eeefed;
	padding: 0;
	margin: 0;
	padding: 5px;
	border-radius: 3px;
	margin: 5px 0 0 0;
}

#searchfield form .biginput {
	width: 600px;
	height: 40px;
	padding: 0 10px 0 10px;
	border: 1px solid #c8c8c8;
	border-radius: 3px;
	color: #000;
	font-weight: normal;
	font-size: 1.5em;
	-webkit-transition: all 0.2s linear;
	-moz-transition: all 0.2s linear;
	transition: all 0.2s linear;
	width: 600px;
	margin: 0 auto;
}

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

.autocomplete-suggestions {
	border: 1px solid #999;
	background: #fff;
	cursor: default;
	overflow: auto;
	height: 220px;
	width: 626px;
	margin: 0 auto;
	display: none;
}

.autocomplete-suggestion {
	padding: 10px 5px;
	font-size: 1.2em;
	white-space: nowrap;
	overflow: hidden;
}

.autocomplete-selected {
	background: #f0f0f0;
}

.autocomplete-suggestions strong {
	font-weight: normal;
	color: #3399ff;
}

.visually-hidden {
	position: absolute !important;
	clip: rect(1px 1px 1px 1px);
	/* IE6, IE7 */
	clip: rect(1px, 1px, 1px, 1px);
	padding: 0 !important;
	border: 0 !important;
	height: 1px !important;
	width: 1px !important;
	overflow: hidden;
}

body:hover .visually-hidden a,
body:hover .visually-hidden input,
body:hover .visually-hidden button {
	display: none !important;
}

#hint {
	position: absolute;
	left: 777px;
	z-index: 10;
	background-color: #fff;
	text-transform: capitalize;
}

#search {
	z-index: 11;
	background-color: #fff;
	position: relative;
	text-transform: capitalize;
}

.button {
	cursor: pointer;
}

.info {
	margin: 0 auto;
}

h1 {
	text-align: center;
}
              
            
!

JS

              
                $(document).ready(function() {
	/*List of suburbs that will act as the list of suggestions for my auto-suggest widget*/
	var suburbs = ["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"];
	/*Counter used to set IDs for each of the suggestions.*/
	var counter = 1;
	/*Array of keys used for the keyboard interactions*/
	var keys = {
		ESC: 27,
		TAB: 9,
		RETURN: 13,
		LEFT: 37,
		UP: 38,
		RIGHT: 39,
		DOWN: 40
	};
	
	/*Event handlers on the search input. One to perform the search and the other to deal with the keyboard interaction*/
	
	$("#search").on("input", function(event) {
		doSearch(suburbs);
	});

	$("#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(suburbs) {

	var query = $("#search").val();
	$("#search").removeAttr("aria-activedescendant");

	/*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 of suggestions
		var results = $.grep(suburbs, function(item) {
			return item.search(RegExp("^" + query, "i")) != -1;

		});
		/*Make sure we have at least 1 suggestion*/
		if (results.length >= 1) {
			/*Start things fresh by removing the suggestions div and emptying the live region before we start*/
			$("#res").remove();
			$('#announce').empty();
			$(".autocomplete-suggestions").show();
			/*Create the listbox to store the suggestions*/
			$(".autocomplete-suggestions").append('<div id="res" role="listbox" tabindex="-1"></div>');
			counter = 1;
		}



		//Add suggestions to the list, limiting the list of displayed suggestions to 5
		for (term in results) {

			if (counter <= 5) {
				$("#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 found" + ", to navigate use up and down arrows");
		}

	} else {
	/*If no results make sure the list does not display*/
		$("#res").remove()
		$('#announce').empty();
		$(".autocomplete-suggestions").hide();
	}

		//Bind click event to suggestions in results
		$("#res").on("click", "div", function() {
			/*When an option is clicked, copy it's text into the input field, then close and remove the list of suggestions*/
			$("#search").val($(this).text());
			$("#res").remove();
			$('#announce').empty();
			$(".autocomplete-suggestions").hide();
			counter = 1;

		});

}

/*Function to deal with the keyborad interactions for the auto-suggest and highlight the currently selected option*/
function doKeypress(keys, event) {
	var highligted = false;
	highligted = $('#res').children('div').hasClass('highligt');
	switch (event.which) {

		case keys.ESC:
			$("#search").removeAttr("aria-activedescendant");
			//$('#hint').val('');
			$("#res").remove();
			$('#announce').empty();
			$(".autocomplete-suggestions").hide();
			break;

		case keys.RIGHT:

			return selectOption(highligted)
			break;

		case keys.TAB:
			$("#search").removeAttr("aria-activedescendant");
			$("#res").remove();
			$('#announce').empty();
			$(".autocomplete-suggestions").hide();
			break;

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

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

		case keys.DOWN:
			event.preventDefault();
			event.stopPropagation();

			return moveDown(highligted);
			break;

		default:
			return;
	}
}
/*Function to move the user up the list of suggestions*/
function moveUp(highligted) {
	var current;
	$("#search").removeAttr("aria-activedescendant");
	
	if (highligted) {
		console.log("Highlighted - " + highligted + "");
		current = $('.highligt');
		current.attr('aria-selected', false);
		current.removeClass('highligt').prev('div').addClass('highligt');
		current.prev('div').attr('aria-selected', true);
		$("#search").attr("aria-activedescendant", current.prev('div').attr('id'));
		highligted = false;
	} else {

		//Go back to the bottom of the list
		current = $("#res").children().last('div');
		current.addClass('highligt');
		current.attr('aria-selected', true);
		$("#search").attr("aria-activedescendant", current.attr('id'));

	}
}
/*Function to move the user down the list of suggestions*/
function moveDown(highligted) {

	var current;
	$("#search").removeAttr("aria-activedescendant");
	
	if (highligted) {
		console.log("Highlighted - " + highligted + "");
		current = $('.highligt');
		current.attr('aria-selected', false);
		current.removeClass('highligt').next('div').addClass('highligt');
		current.next('div').attr('aria-selected', true);
		$("#search").attr("aria-activedescendant", current.next('div').attr('id'));
		highligted = false;
	} else {

		//Go back to the top of the list
		current = $("#res").children().first('div');
		current.addClass('highligt');
		current.attr('aria-selected', true);
		$("#search").attr("aria-activedescendant", current.attr('id'));
	}
}

/*Function to select the users chosen option*/
function selectOption(highligted) {
	if (highligted) {
		$("#search").removeAttr("aria-activedescendant");
		$('#search').val($('.highligt').text());
		$('#search').focus();
		$("#res").remove();
		$('#announce').empty();
		$(".autocomplete-suggestions").hide();
	} else {
		return;
	}
}
              
            
!
999px

Console