Friday, March 15, 2013

Keyup and Keydown on the LI

When you press arrow key up or down your LI should be heighlighed according to movements of arrow key.
<style type="text/css">/*Add this in master page*/

.selectedMahesh

{

background: #ccc;

}

</style>

<script type="text/javascript">

 

function Test(e) {

var $listItems = $('[id=maheshUL] li');/*Use to get UL selector should be accroding to DOM*/



var key = e.keyCode,

$selected = $listItems.filter('.selectedMahesh'),

$current;

if (key != 40 && key != 38) return;

$listItems.removeClass('selectedMahesh');

if (key == 40) // Down key

{

if (!$selected.length || $selected.is(':last-child')) {

$current = $listItems.eq(0);

}

else {

$current = $selected.next();

}

}

else if (key == 38) // Up key

{

if (!$selected.length || $selected.is(':first-child')) {

$current = $listItems.last();

}

else {

$current = $selected.prev();

}

}

$current.addClass(
'selectedMahesh');/*Add the class which is used to heighligh the element*/

}

</script>

<input id="input_city" type="text" onkeydown="Test(event);" />

<div >

<ul id='maheshUL'>

<li >New York</li>

<li >London</li>

<li >Paris</li>

<li >Sydney</li>

</ul>

</div>

No comments: