Vijay Vijay - 1 year ago 100
CSS Question

Remove selected class applied to list item by arrow key navigation when mouse hover style is applied

When UP/DOWN Arrow key is pressed in text box, selected class is applied to the list item. If I move the mouse pointer over list item and press up/down arrow key at the same time, both hover and selected class is applied to the list item. How to switch hover and selected class similar to select input option?

$('#college').keyup(function(e) {

var $listItems = $('.field-wrap li');
var key = e.keyCode,
$selected = $listItems.filter('.selected'),


var menu = $('#college_list');
var height = $selected.outerHeight();
var top = menu.scrollTop();
var menuHeight = menu[0].scrollHeight;

if (key == 40) // Down key
if (!$selected.length || $':last-child')) {
$current = $listItems.eq(0);
} else {
$current = $;
menu.scrollTop(top + height);


if (key == 38) // Up key
if (!$selected.length || $':first-child')) {
$current = $listItems.last();
menu.scrollTop(menuHeight + height);
} else {
$current = $selected.prev();
menu.scrollTop(top - height);


.field-wrap ul {
width: 93%;
margin-top: 1px;
border: 1px solid #3498DB;
position: absolute;
z-index: 9;
background: white;
list-style: none;
max-height: 100px;
overflow-y: auto;
.field-wrap ul li {
padding: 2px;
border: solid grey;
border-width: 0 0 2px 0;
.field-wrap ul li:hover {
background: #2980B9;

<div class="field-wrap">
<input type="text" id="college" placeholder="Name" required autocomplete="off" />
<ul id="college_list">

Answer Source

I'm afraid in this case you will have to replace the css :hover with the mousemove event:

$('#college_list li').mousemove(function() {
   $('.field-wrap li').removeClass('selected');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download