Vijay Vijay - 2 months ago 15
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?

http://jsfiddle.net/AyAZx/790/



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

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

$listItems.removeClass('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 || $selected.is(':last-child')) {
$current = $listItems.eq(0);
menu.scrollTop(0);
} else {
$current = $selected.next();
menu.scrollTop(top + height);
}

$current.addClass('selected');
}

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

});

.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">
<li>abc</li>
<li>def</li>
<li>asdff</li>
<li>dasdf</li>
<li>asdef</li>
<li>asdf</li>
<li>asf</li>
<li>asdef</li>
</ul>
</div>




Answer

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');
   $(this).addClass('selected');
});
Comments