1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
<%@ page pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/styles/style.css" />
<title>AutoCompl</title>
</head>
<body>
<form method="post" action="">
<input type="search" name="searchbar" id="searchbar" />
</form>
<div id="autoZone"></div>
<script>
(function() {
var input = document.getElementById("searchbar");
input.addEventListener("keyup",function(e) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'base?param1='+e.currentTarget.value,true);
xhr.send(null);
xhr.addEventListener('readystatechange', function() {
if (xhr.readyState === xhr.DONE) {
var spans = xhr.responseXML.getElementsByTagName('span');
document.getElementById('autoZone').innerHTML="";
for(var i =0, l=spans.length; i<l; i++){
console.log(xhr.responseText);
spans[i].setAttribute("class", "propos");
document.getElementById('autoZone').appendChild(spans[i]);
document.getElementById('autoZone').appendChild(document.createElement('br'));
}
addListen();
}
}, false);
})
})();
//gère le surlignement
function addListen() { // Utilisation d une IIFE pour éviter les variables globales.
var propos = document.querySelectorAll('.propos');
console.log(propos);
propos[0].setAttribute('style',"color:white;background:blue;");
var current = propos[0];
var indCur=0;
var nbPro = propos.length;
for(i=0;i<nbPro;i++){
(function(i){
propos[i].addEventListener('mouseover',function(e){
current.setAttribute('style', "");
e.currentTarget.setAttribute('style',"color:white;background:blue;");
current=e.currentTarget;
indCur=i;
});
})(i);
};
document.addEventListener('keyup',function(e){
var code= e.keyCode;
if(code==38){
indCur--;
if(indCur<0){
indCur=nbPro-1;
}
current.setAttribute('style', "");
propos[indCur].setAttribute('style',"color:white;background:blue;");
current=propos[indCur];
}
if(code==40){
indCur++;
if(indCur>nbPro-1){
indCur=0;
}
current.setAttribute('style', "");
propos[indCur].setAttribute('style',"color:white;background:blue;");
current=propos[indCur];
}
});
}
</script>
</body>
</html> |
Partager