Reputation: 37
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;
});
Upvotes: 1
Views: 872
Reputation: 348972
Use keydown
or keyup
. The Keypress
event listener doesn't recognise non-character keys (the key code of the arrow keys at keypress
are 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: elseif
is not a valid JavaScript expression. Use else if
(with a space in between else
and if
) instead.
$(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').keydown(function(e)
{
if(e.which == 37)
{
$(this).removeClass('highlight');
$(this).prev().addClass('highlight');
}
else if(e.which == 39)
{
$(this).removeClass('highlight');
$(this).next().addClass('highlight');
}
return false;
});
});
});
Upvotes: 2