Does anyone have any experience in creating their own AJAX auto suggest text box with full keyboard support?
I have successfully created the auto suggest aspect by plugging in to a SQL DB and displaying results but the only way to interact with the search results is to use the mouse. I want to be able to scroll up/down with the keyboard and use the enter key to select the item and be redirected to the relevant page.
I have seen countless articles and help forum pages detailing how to scroll through HTML elements with the up/down arrows, but nothing explaining how the enter key can be incorporated into selecting the item and redirecting to the relevant page.
I am aware of all the auto suggest plugins I can use, but I have come this far creating my own and I want to be able to add extra content to the results rather than be fixed to someone else's work.
If anyone could help me out by pointing me in the right direction I would be very grateful.
Cheers
This answer definitely falls under the category 'point in the right direction', because I don't know if you already have code and what that looks like (if it exists).
You said you already created a dropdown with suggestions, so I'll leave out CSS and JS for styling and positioning.
Let's assume the dropdown consists of this markup:
<div id="suggestiondropdown">
<span class="suggestion" data-page="[URL of page]">Suggestion 1</span>
<span class="suggestion" data-page="[URL of page]">Suggestion 2</span>
<span class="suggestion" data-page="[URL of page]">Suggestion 3</span>
<span class="suggestion" data-page="[URL of page]">Suggestion 4</span>
<span class="suggestion" data-page="[URL of page]">Suggestion 5</span>
</div>
With this JS you should be able to move between the suggestions with the arrow keys:
var suggestions = document.querySelectorAll(".suggestion"); // Now suggestions is an array with the spans
var index = 0;
document.onkeypress = function(e) {
// Style the selected as normal here:
suggestions[index].style.backgroundColor = "#FFFFFF";
if (e.keyCode == 38) { // UP!
if (index <= 0) index = suggestions.length;
index--;
}
else if (e.keyCode == 40) { // DOWN!
if (index >= suggestions.length -1) index = -1;
index++;
}
else if (e.keyCode == 13) { // ENTER!
var page = suggestions[index].dataset.page;
window.location.href = page; // Or with relative URLs, first prepend the base URL.
}
// Style the selected one as selected here.
// I don't know how you want it, so I'll just give the selected one a blue background.
suggestions[index].style.backgroundColor = "#0000FF"; // Never mind the ugly shade
}
Untested