Save contentEditable into html file with javascript - javascript

How can I save contenteditable element with javascript(no PHP) into actual HTML code? So I can edit content whenever even in offline mode.
Like when you click "save button" it replace old file with new one(text with changes).
If there is a way to make this work in offline mode with any other programming lang please suggest.
I found a few examples but they were all made with PHP.
Also, I will post code. In this code, you are able to edit the file with javascript and save it. But problem is that it does not save into actual HTML code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<style type="text/css">
body{
font-family: "Dosis";
font-size: 1.3em;
line-height: 1.6em;
}
.headline{
font-size: 2em;
text-align: center;
}
#wrapper {
width: 600px;
background: #FFF;
padding: 1em;
margin: 1em auto;
box-shadow: 0 2px 5px rgba(0,0,0,0.3);
border-radius: 3px;
}
button {
border: none;
padding: 0.8em;
background: #F96;
border-radius: 3px;
color: white;
font-weight: bold;
margin: 0 0 1em;
}
button:hover, button:focus {
cursor: pointer;
outline: none;
}
#editor {
padding: 1em;
background: #E6E6E6;
border-radius: 3px;
}
</style>
<body>
<div id="wrapper">
<section>
<h1 class="headline">contentEditable Demonstration</h1>
<button id="editBtn" type="button">Edit Document</button>
<div id="editDocument">
<h1 id="title">A Nice Heading.</h1>
<p>Last Edited by <span id="author">Monty Shokeen</span>
</p>
<p id="content">You can change the heading, author name and this content itself. Click on Edit Document to start editing. At this point, you can edit this document and the changes will be saved in localStorage. However, once you reload the page your changes will be gone. To fix it we will have to retrieve the contents from localSotrage when the page reloads.</p>
</div>
</section>
</div>
<script>
var editBtn = document.getElementById('editBtn');
var editables = document.querySelectorAll('#title, #author, #content');
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem('title') !== null) {
editables[0].innerHTML = localStorage.getItem('title');
}
if (localStorage.getItem('author') !== null) {
editables[1].innerHTML = localStorage.getItem('author');
}
if (localStorage.getItem('content') !== null) {
editables[2].innerHTML = localStorage.getItem('content');
}
}
editBtn.addEventListener('click', function(e) {
if (!editables[0].isContentEditable) {
editables[0].contentEditable = 'true';
editables[1].contentEditable = 'true';
editables[2].contentEditable = 'true';
editBtn.innerHTML = 'Save Changes';
editBtn.style.backgroundColor = '#6F9';
} else {
// Disable Editing
editables[0].contentEditable = 'false';
editables[1].contentEditable = 'false';
editables[2].contentEditable = 'false';
// Change Button Text and Color
editBtn.innerHTML = 'Enable Editing';
editBtn.style.backgroundColor = '#F96';
// Save the data in localStorage
for (var i = 0; i < editables.length; i++) {
localStorage.setItem(editables[i].getAttribute('id'), editables[i].innerHTML);
}
}
});
</script>
</body>
</html>

You'll want to use something like the downloadInnerHtml function as described here. Ideally you'll probably also want to strip out the script tag and content editable attribute before exporting because you won't want the final html page to be editable

Related

Load stylesheet with javascript and localStorage

I'm using a Jekyll website, doesn't really matter because this is a static page, I just write it as additional info.
Desired behavior:
I want to load my stylesheet via javascript, so it can depend of a local stored value, let's say dark and light.
I have done a little test of loading it by JS with the following code (which works).
GREEN
<head>
...
<link rel="stylesheet" href="/assets/css/{{'light'}}.css">
...
</head>
This loads the CSS file called "light" as expected.
But now I want to depend of the localStorage, with a variable theme that has light as value. I tried the following:
RED
<head>
...
<script>
var storedTheme = window.localStorage.getItem('theme'); //Tested and working in console
theme = storedTheme ? storedTheme : 'light'; //global variable (also readable in console)
</script>
<link rel="stylesheet" href="/assets/css/{{theme}}.css"> <!-- cant read global variable -->
...
</head>
Using global variables doesn't work, it gives me a 404 error as the stylesheet path is /assets/css/.css.
After that I thought that maybe creating an element would do the trick and I created one manually to test it:
RED
<head>
...
<p id="theme" style="display:none;">dark</p>
<link rel="stylesheet" href="/assets/css/{{document.getElementById('theme').innerHTML}}.css">
...
</head>
And nope, the path still appears as: /assets/css/.css
If you change styles on the <body> you get FOUC (Flash Of Unstyled Content). Try using a close equivalent like <main> and spread it 100% x 100% and <html> and <body> as well, but give them margin and padding of 0 in order to ensure <main> covers them completely.
The [disabled] attribute for the <link> is the best way of toggling them because they are still loaded but inert. Also, in the example there is a function called loadTheme(e) that is loaded on the 'DOMContentLoaded' event which insures that all of the DOM is loaded before hand. The example below will not work because localStorage is blocked on SO. There is a functioning example on Plunker. To test it:
Click the green Preview button.
Another frame should appear on the right. Within the frame is the webpage example click the ☀️ button.
It should be in dark mode now. Next, click the refresh ⟳ button located in the mini-toolbar within the frame or press ctrl+enter for Windows OS or ⌥+return for Mac OS.
The page should still be in dark mode. 👍
/* night.css
main {
background: #000;
color: #fff;
}
*/
/* default.css */
:root {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font: 1ch/1.5 'Segoe UI';
}
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
font-size: 4ch;
}
main {
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #fff;
color: #000;
}
form {
width: 80vw;
margin: 20px auto;
}
fieldset {
width: max-content;
min-height: 25px;
margin-left: auto;
padding: 0 1.5px 1.5px;
border-radius: 8px;
background: inherit;
color: inherit;
}
button {
display: block;
width: 100%;
height: 100%;
border: 0;
font-size: 4rem;
text-align: center;
background: transparent;
cursor: pointer;
}
#theme::before {
content: '☀️';
}
.night #theme::before {
content: '🌙';
}
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href='lib/default.css' rel='stylesheet'>
<link class='night' href='lib/night.css' rel='stylesheet' disabled>
<style></style>
</head>
<body>
<main>
<form id='UI'>
<fieldset name='box'>
<legend>Theme</legend>
<button id='theme' type='button'></button>
</fieldset>
<p>Click the "Theme" switch to toggle between `disabled` `true` and `false` on `night.css` and `light.css` `
<link>`s.</p>
</form>
</main>
<script>
const UI = document.forms.UI;
const M = document.querySelector('main');
const L = document.querySelector('.night')
const switchTheme = e => {
const clk = e.target;
if (clk.matches('button')) {
M.classList.toggle('night');
L.toggleAttribute('disabled');
}
let status = M.className === 'night' ? 'on' : 'off';
localStorage.setItem('theme', status);
};
const loadTheme = e => {
let cfg = localStorage.getItem('theme');
if (cfg === 'on') {
M.classList.add('night');
L.removeAttribute('disabled');
} else {
M.classList.remove('night');
L.setAttribute('disabled', true);
}
};
UI.addEventListener('click', switchTheme);
document.addEventListener('DOMContentLoaded', loadTheme);
</script>
</body>
</html>

Dark Mode not working during loading time

I'm trying to make a dark mode toggle button which can toggle between dark and light mode on click, User preference is also stored using localStorage. The user should manually press the button to toggle to other mode. If the user's choice is dark mode, Every page will be in dark mode and it doesn't turn to light mode on refreshing. Everything looks fine upto now but the real issue comes with loading time. The load time of a page is nearly 1 second and in that time, Page appears to be in light mode even if user's choice is dark mode. I don't want that to happen. I want loading time section in dark mode if user's choice is dark.
This is my current code:
<script>
const body = document.querySelector('body');
function toggleDark() {
if (body.classList.contains('dark')) {
body.classList.remove('dark');
localStorage.setItem("theme", "light");
} else {
body.classList.add('dark');
localStorage.setItem("theme", "dark");
}
}
if (localStorage.getItem("theme") === "dark") {
body.classList.add('dark');
}
</script>
<style>
body {background-color: #ffffff}
body.dark {background-color: #000000; color: #ffffff}
</style>
<button class="dark-mode" id="btn-id" onclick="toggleDark()"></button>
Another alternative is to load the script in the <head> element, and toggle the class on html element
To do so, you use document.documentElement.classList as that is the HTML element
Then change your CSS to
html.dark body {}
etc .. the class selector on HTML
html body {background-color: #ffffff}
html.dark body {background-color: #000000; color: #ffffff}
<script>
const body = document.querySelector('body');
function toggleDark() {
if (document.documentElement.classList.contains('dark')) {
document.documentElement.classList.remove('dark');
//localStorage.setItem("theme", "light");
} else {
document.documentElement.classList.add('dark');
//localStorage.setItem("theme", "dark");
}
}
//if (localStorage.getItem("theme") === "dark") {
document.documentElement.classList.add('dark');
//}
</script>
<button class="dark-mode" id="btn-id" onclick="toggleDark()">DARK</button>
Due to restrictions, localStorage is unavailable on stack overflow - uncomment those lines to see it work
Or - see https://jsfiddle.net/e9zg2p4c/
Store it to backend database. Then when serving HTML content put proper class/style for your elements. This will remove flickering between loading times:
<!DOCTYPE html>
<html>
<head>
<style>
/* Use Less/Sass for better management */
.theme.light {
background-color: #ffffff;
}
.theme.dark {
background-color: #000000; color: #ffffff;
}
</style>
</head>
<body class="theme <?= $user->themeName; ?>">
</body>
</html>
A little more tricky to toggle AND have a default theme
Note the localStorage calls do not work here at SO
working example
In the code below replace
const theme = "dark"; with
localStorage.getItem("theme") || "light"
and uncomment // localStorage.setItem("theme", body.classList.contains("dark") ? "light" : "dark");
on your server
.dark { background-color: black; color: white; }
<!DOCTYPE html>
<html>
<head>
<style>
.theme {
background-color: white;
color: black;
}
</style>
<script>
const theme = "dark"; // localStorage.getItem("theme") || "theme"
if (theme === "dark") {
const st = document.createElement("style");
st.id="darkStyle";
st.innerText = `body.theme { background-color: black; color: white; }`;
document.querySelector("head").appendChild(st);
}
window.addEventListener("load", function() {
document.getElementById("toggleTheme").addEventListener("click", function() {
const body = document.querySelector("body");
const darkStyle = document.getElementById("darkStyle");
if (darkStyle) {
darkStyle.remove(); // remove stylesheet now we know what the user wants
body.classList.remove("theme");
}
const theme = body.classList.contains("theme");
body.classList.toggle('theme',!theme);
body.classList.toggle('dark',theme);
// localStorage.setItem("theme", theme ? "light" : "dark"); // uncomment on your server
});
})
</script>
</head>
<body class="theme">
Here is the body
<button id="toggleTheme" type="button">Toggle theme</button>
</body>
</html>
Given that the only real difference between light and dark is the colours, why not simply create css variables for each colour you are going to use and use javascript to change the values of the variables. This way, once you have defined the classes using the variables in the appropriate places, changing the variable values changes the classes automatically. The choice of "dark" and "light" can be stored in whatever way is available to you - localStorage, cookies or backend etc - and you simply set the appropriate colours to the css variables when the page is being loaded. There's no need for separate definitions for each class and, as a developer, it allows you to quickly test the colour schemes without having to manually change every class one by one.
function changeTheme(t) {
if (t == "dark") {
document.documentElement.style.setProperty("--backgroundcolour", "black");
document.documentElement.style.setProperty("--fontcolour", "white");
} else {
document.documentElement.style.setProperty("--backgroundcolour", "white");
document.documentElement.style.setProperty("--fontcolour", "black");
}
}
:root {
--backgroundcolour:black;
--fontcolour:white;
}
body {
background-color:var(--backgroundcolour);
color:var(--fontcolour);
}
span {
background-color:var(--backgroundcolour);
color:var(--fontcolour);
}
div {
background-color:var(--backgroundcolour);
color:var(--fontcolour);
}
table {
background-color:var(--backgroundcolour);
color:var(--fontcolour);
}
<button onclick="changeTheme('dark');">Use dark theme</button><button onclick="changeTheme('light');">Use light theme</button>
<hr>
<span>Text in a span</span>
<hr>
<div>Text in a div</div>
<hr>
<table>
<tbody>
<tr><td>Text in a table</td></tr>
</tbody>
</table>
If you want to use checkbox, this solution for you.
if you want the value to remain unchanged, use localStorage. If you want a dark mode where you have values ​​disappear when you close a tab or browser, use sessionStorage.
const check = document.getElementById('chk');
check.addEventListener('change', () => {
document.body.classList.toggle('dark');
localStorage.darkMode=!localStorage.darkMode;
});
window.onload=function() {
if(localStorage.darkMode) document.body.classList.toggle('dark');
}
#modeSwitcher{
margin: 5% 50%;
}
#modeSwitcher .checkbox {
opacity: 0;
position: absolute;
}
#modeSwitcher .checkbox:checked + .label .ball{
transform: translateX(35px);
}
#modeSwitcher .checkbox:checked + .label .ball::after{
content: '';
position: absolute;
background-color: #0A0E27;
width: 13px;
height: 13px;
border-radius: 50%;
bottom: 50%;
left: -5%;
transform: translateY(50%);
}
#modeSwitcher .label {
background-color: #0A0E27;
border-radius: 50px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
padding: 5px;
margin: 0;
position: relative;
height: 16px;
width: 50px;
transform: scale(1.5);
}
#modeSwitcher .label .fa-moon{
color:#0A0E27 ;
}
#modeSwitcher .label .ball {
background-color: #FDC503;
border-radius: 50%;
position: absolute;
top: 3px;
left: 3px;
height: 20px;
width: 20px;
transform: translateX(0px);
transition: transform 0.2s linear;
}
body{
background-color: #fff;
}
body.dark{
background-color: black;
}
<div id="modeSwitcher">
<input type="checkbox" class="checkbox" id="chk" />
<label class="label" for="chk">
<i class="fas fa-moon"></i>
<div class="ball"></div>
</label>
</div>

get file object from called window javascript

I am trying to open a window and process the file in the calling JavaScript. I can pass the file name using localStorage but if I return the file I can't get it right.
I can't use this solution due to restrictions of the system I am calling the JavaScript from:
var fileSelector = document.createElement('input');
fileSelector.setAttribute('type', 'file');
fileSelector.click();
Can a file object be passed using localStorage or should I use another method?
My code is:
<!DOCTYPE html>
<html>
<script language="JavaScript">
function testInjectScript2(){
try {
var myhtmltext =
'<input type="file" id="uploadInput3" name=\"files[]" onchange=\'localStorage.setItem("myfile",document.getElementById("uploadInput3").files[0]);\' multiple />';
console.log("myhtmltext="+myhtmltext);
var newWin2 = window.open('',"_blank", "location=200,status=1,scrollbars=1, width=500,height=200");
newWin2.document.body.innerHTML = myhtmltext;
newWin2.addEventListener("unload", function (e) {
if(localStorage.getItem("myfile")) {
var f = localStorage.getItem("myfile");
alert ('in function.f='+f);
alert ('in function.f.name='+(f).name);
localStorage.removeItem("myfile");
}
});
} catch (err) {
alert(err);
}
}
</script>
<body>
<input type="button" text="testInjectScript2" onclick="testInjectScript2()" value="testInjectScript2" />
</body>
</html>
First of all, welcome to SO. If I get you right, you want to upload a file using a new window and get that file using localStorage onto your main page. This is a possible solution. However, please do also note that the maximum size of the localStorage can vary depending on the user-agent (more information here). Therefore it is not recommend to use this method. If you really want to do this, please have a look at the first snippet.
var read = document.getElementById("read-value"), open_win = document.getElementById("open-win"), win, p = document.getElementById("file-set");
open_win.addEventListener("click", function(){
win = window.open("", "", "width=200,height=100");
win.document.write(
'<input id="file-input" type="file"/>' +
'<script>' +
'var input = document.getElementById("file-input");' +
'input.addEventListener("change", function(){window.localStorage.setItem("file", input.files[0]);})'+
'<\/script>'
);
})
read.addEventListener("click", function(){
var file = window.localStorage.getItem("file");
if(file){
p.innerText = "file is set";
}else{
p.innerText = "file is not set";
}
})
<button id="open-win">Open window</button>
<br><br>
<!-- Check if file is set in localStorage -->
<button id="read-value">Check</button>
<p id="file-set" style="margin: 10px 0; font-family: monospace"></p>
<i style="display: block; margin-top: 20px">Note: This only works locally as SO snippets lack the 'allow same origin' flag. i.e. just copy the html and js into a local file to use it.</i>
However, why not use a more elegant solution:
Simply using a modal. When the input value changes you can simply close the modal and get the file value without all the hassle of a localStorage.
// Get the modal, open button and close button
var modal = document.getElementById('modal'),
btn = document.getElementById("open-modal"),
span = document.getElementById("close"),
input = document.getElementById("file-input"),
label = document.getElementById("input-label"), file;
// When the user clicks the button, open the modal
btn.addEventListener("click", function() {
modal.style.display = "block";
})
// When the user clicks on <span> (x), close the modal
span.addEventListener("click", function() {
modal.style.display = "none";
})
input.addEventListener("change", function(){
file = input.files[0];
modal.style.display = "none";
//Change value of the label for nice styling ;)
label.innerHTML = input.files[0].name;
//do something with your value
})
// When the user clicks anywhere outside of the modal, close it
window.addEventListener("click", function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
})
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 10px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
.modal h2 {
font-family: sans-serif;
font-weight: normal;
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
/* Input styles, added bonus */
.file-input {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
.file-input + label {
font-size: 1.25em;
font-weight: 700;
padding: 10px 20px;
border: 1px solid #888;
display: inline-block;
cursor: pointer;
font-family: sans-serif;
}
.file-input:focus + label,
.file-input + label:hover {
background-color: #f7f7f7;
}
<!-- Trigger/Open The Modal -->
<button id="open-modal">Open Modal</button>
<!-- The Modal -->
<div id="modal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span id="close" class="close">×</span>
<h2><i>Upload a file?</i></h3>
<input id="file-input" name="file-input" class="file-input" type="file"/>
<label id="input-label" for="file-input">Upload a file</label>
</div>
</div>
Hope it helps! Let me know!
Cheers!

How do I display a DIV when an anchor is active in HTML

How do I make the following code only display when the url ends in #404?
<!--404 code-->
<style>
.div1 {
width: 300px;
height: 100px;
border: 1px solid blue;
border-color: #ff0263;
box-sizing: border-box;
}
</style>
<body>
<font face="century gothic">
<div class="div1" name="div1">
<span id='close' style="cursor:pointer" onclick='this.parentNode.parentNode.parentNode.removeChild(this.parentNode.parentNode); return false;'>x</span> The vite you were looking for could not be found. <button class="button button5">What do I do now?</button></div>
</font>
<script>
window.onload = function() {
document.getElementById('close').onclick = function() {
this.parentNode.parentNode.parentNode
.removeChild(this.parentNode.parentNode);
return false;
};
};
</script>
<style>
#close {
float: right;
display: inline-block;
padding: 2px 5px;
background: #ccc;
}
#close:hover {
float: right;
display: inline-block;
padding: 2px 5px;
background: #ccc;
color: #fff;
}
</style>
<script>
$(document).ready(function() {
$("#id1").click(function() {
$(".div1").css('display', 'block');
});
});
</script>
I run this website called Vite - vite.website (Google: Vite Flash Engine). and if I could set it up so that when it reaches a 404, it will redirect to vite.website/#404. How do I make the following code visible only when the anchor, #404 is active?
Thanks!
This is css.but you can use jquery.
you can get the hash of the current url of the page and use if statement for your aim.
you can get the hash location of a webpage using
window.location.hash
So, maybe something like this can work (assuming you're using jQuery)
function hashIs404() {
var hash = location.hash.slice(-1);
if (hash === "404") {
//Display things
//$(selector).addClass(classname); recommended
} else {
//Hash is not 404
//$(selector).removeClass(classname); recommended
}
}
and call this function hashIs404(); by binding it to window.onload:
window.onload = hashIs404;
As for actually displaying it, use the if case and
$("head").append("<link rel='stylesheet' href='stylesheet-location.css');
Hope I could help if not entirely solving the issue :)

AUTO-SUGGESTION keyboard use

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Auto Suggest</title>
<script type="text/javascript" src="jquery-1.2.1.pack.js"></script>
<script type="text/javascript">
var stringcount = 0;
var st = "";
var vv = "f";
function lookup2(e,inpstring)
{
lookup1(e.keyCode,inpstring);
}
function lookup1(j,inputstring)
{
var x= inputstring.length;
st = inputstring ;
if (inputstring.charAt(parseInt(x,10)-1) == " ")
{
stringcount = stringcount + 1;
}
else
{
var mySplitResult = inputstring.split(" ");
var stringtemp = "" ;
var w = 0;
for (w =0 ; w < stringcount ;w++)
{
stringtemp = stringtemp+ " "+ mySplitResult[w];
}
st = stringtemp;
lookup(mySplitResult[stringcount],inputstring);
}
}
function lookup(inputString,i) {
if(inputString.length == 0) {
// Hide the suggestion box.
$('#suggestions').hide();
} else {
$.post("rpc.php", {queryString: ""+inputString+"" }, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
} // lookup
function fill(thisValue) {
$('#inputString').val(st.substring(1,st.length)+" "+thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
<style type="text/css">
body {
font-family: Helvetica;
font-size: 11px;
color: #000;
}
h3 {
margin: 0px;
padding: 0px;
}
.suggestionsBox {
position: relative;
left: 30px;
margin: 10px 0px 0px 0px;
width: 200px;
background-color: #212427;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
border: 2px solid #000;
color: #fff;
}
.suggestionList {
margin: 0px;
padding: 0px;
}
.suggestionList li {
margin: 0px 0px 3px 0px;
padding: 3px;
cursor: pointer;
}
.suggestionList li:hover {
background-color: #659CD8;
}
</style>
</head>
<body>
<div>
<form>
<div>Type your county here:<br />
<input type="text" size="30" value="" id="inputString" onkeyup="lookup2(event,this.value);" onblur="" />
</div>
<div class="suggestionsBox" id="suggestions" style="display: none;">
<img src="upArrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList"> </div>
</div>
</form>
</div>
</body>
</html>
This is the code i am using. The auto-suggestion box is accessed by clicking on the desired option. How can i scroll through the option by using the up/down keys of the keyboard and select an option by using enter?
It looks like (because you have not quoted the really important code) that your server side ajax endpoint returns an HTML unordered list and this is pasted into the suggestionList div. That's going to be my assumption. Your CSS allows for the hover pseudo-selector so mouse support looks good.
For keyboard support, you are going to have add an event handler for the keypress event, probably on the document. Add the handler when the suggestion box is displayed, remove it when it is dismissed.
The event handler will have to track the up and down arrow keys as well as enter. You will have to add and remove a special class (or maybe an id) on the li element that is currently selected, which means you will have to track how many elements there are to scroll through, and which one is the currently highlighted one. So, if you see the down arrow key, add one to the current index (if you're at the last one, ignore the key). Remove the special class from the li element you just left and add it to the new one (obviously style the class accordingly in your CSS). When the enter key is pressed you know which element is selected, so return it, or do what you want with it.

Categories

Resources