Adding A Limit To Moving A Div With Arrow Keys
Hi I have added in functionality (found on stackoverflow) to make my div move left or right once the user holds down one of the arrow keys. All works as it should. I want to know i
Solution 1:
Sure, take a look at this fiddle: http://jsfiddle.net/ArtBIT/V7qcK/
varKEY = {
LEFT: 37,
RIGHT: 39
}
var boundaries = {
left: 0,
right: 200
}
$(document).keydown(function(e) {
var position = $('#block').position();
switch (e.which) {
caseKEY.LEFT:
$('#block').stop().animate({
left: Math.max(boundaries.left, position.left - 50)
});
break;
caseKEY.RIGHT:
$('#block').stop().animate({
left: Math.min(boundaries.right, position.left + 50)
});
break;
}
});
Or this one http://jsfiddle.net/ArtBIT/8PWCR/1/ for 2D movement
Solution 2:
Get the current offset
and then handle it:
var max = 1000;
$(document).keydown(function(e) {
switch (e.which) {
case37:
if($('#block').offset().left > 50)
{
$('#block').stop().animate({ left: '-=50' });
}
break;
case39:
if($('#block').offset().left < (max - 50)
{
$('#block').stop().animate({ left: '+=50' });
}
break;
}
});
Post a Comment for "Adding A Limit To Moving A Div With Arrow Keys"