How do I get the left and right arrow keys to work in this situation using jQuery?
$(document).ready(function()
{
$('#container').click(function()
{
var totalWidth = 0;
var sizeWidth = $('#insertData1').outerWidth();
$('#ul_a li').each(function()
{
var widthS = $(this).width();
var textW = $(this).text();
var widthN = parseInt(widthS,10);
if((totalWidth + widthN) < sizeWidth)
{
totalWidth = totalWidth + widthN;
$('#ul_b').append('<li>' + textW + '</li>');
}
else
{
return false;
}
});
$('#ul_b li').hover(function()
{
$(this).addClass('highlight');
}, function()
{
$(this).removeClass('highlight');
});
$('#ul_b li').keypress(function(e)
{
if(e.which == 37)
{
$(this).removeClass('highlight');
$(this).prev().addClass('highlight');
}
elseif(e.which == 39)
{
$(this).removeClass('highlight');
$(this).next().addClass('highlight');
}
return false;
});
});
});
By the way, even tried using keyup and get the same problem…
$('#ul_b li').keyup(function(e)
{
if(e.keyCode == 37)
{
$(this).removeClass('highlight');
$(this).prev().addClass('highlight');
}
elseif(e.keyCode == 39)
{
$(this).removeClass('highlight');
$(this).next().addClass('highlight');
}
return false;
});
Use
keydownorkeyup. TheKeypressevent listener doesn’t recognise non-character keys (the key code of the arrow keys atkeypressare zero). Coincidentally, I’ve just written an arrow key script for another question.See this Fiddle for an example of the key code script: http://jsfiddle.net/ATUEx/ (Question)
Note: I’ve found (and fixed) another error:
elseifis not a valid JavaScript expression. Useelse if(with a space in betweenelseandif) instead.Your fixed code: