How to Move a Div with Arrow Keys

how to move a div with arrow keys

var pane = $('#pane'),
box = $('#box'),
w = pane.width() - box.width(),
d = {},
x = 3;

function newv(v,a,b) {
var n = parseInt(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0);
return n < 0 ? 0 : n > w ? w : n;
}

$(window).keydown(function(e) { d[e.which] = true; });
$(window).keyup(function(e) { d[e.which] = false; });

setInterval(function() {
box.css({
left: function(i,v) { return newv(v, 37, 39); },
top: function(i,v) { return newv(v, 38, 40); }
});
}, 20);
#pane {
position: relative;
width: 300px;
height: 300px;
border: 2px solid red;
}

#box {
position: absolute;
top: 140px;
left: 140px;
width: 20px;
height: 20px;
background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="pane">
<div id="box"></div>
</div>

Continously move div with arrow keys

This could be an approach for you:

var pressed = false;
$(document).keydown(function(e) {
if(!pressed){ //only start animation once
width = $(this).width();
height = $(this).height();
switch (e.which) {
case 37:
$('div').stop().animate({
left: '-=' + width //allow the user the move the div over the whole doc
}, 2000); //left arrow key
break;
// and so on
}
}
pressed = true;
}).keyup(function(){
$('div').stop(); // stop the current animation
pressed = false;
});

perhaps you have to change the variables width and height to fit in your needs.

DEMO

How use keyboard arrow keys to move a div 100px left/right respectively

As a rule keypress events go to an input or some control that has focus, if you need them generally on a page, which is a sometimes a little frowned upon due to removing standard behavior, then bind the keydown event to the whole document.

$('body').keydown(function(event) {
switch (event.keycode) {
case 37: // left arrow key
$('#bottom_arrow').animate({ 'left': '-=100' });
break;
case 39: // right arrow key
$('#bottom_arrow').animate({ 'left': '+=100' });
break;
}
});

I have used keydown, rather than keypress as a user would expect it to trigger whilst pressing the key.

How to make a specific div move with arrow keys (specified by button clicked)

Here is a solution. I have edited the values a bit, but you can easily change them back.

const buttonOne = document.getElementById('button-one');
const buttonTwo = document.getElementById('button-two');

const elementOne = document.getElementById('one');
const elementTwo = document.getElementById('two');

buttonOne.addEventListener('click', clickOnButtonOne);
buttonTwo.addEventListener('click', clickOnButtonTwo);

let selectedElement = null;

function clickOnButtonOne() {
selectedElement = elementOne;
}

function clickOnButtonTwo() {
selectedElement = elementTwo;
}

document.onkeydown = detectKey;

function detectKey(e) {
if (selectedElement) {
if (e.keyCode == '39') {
var posLeft = selectedElement.offsetLeft
selectedElement.style.left = (posLeft + 50) + "px"
}
if (e.keyCode == '38') {
var posTop = selectedElement.offsetTop
selectedElement.style.top = (posTop - 50) + "px"
}
}
}
.counter {
border-radius: 50%;
width: 20px;
height: 20px;
position: absolute;
transition: top linear 0.6s, left linear 0.6s;
font-size: 20px;
font-weight: bold;
text-align: center;
padding: 20px;
top: 500px;
left: 60px;
background-color: red;
}
<button id="button-one" onclick="one">Move One</button>
<button id="button-two" onclick="two">Move Two</button>

<div class="counter" id="one">1</div>
<div class="counter" id="two">2</div>

Move a div within another div with arrow keys

I have tested the code and found that when you are near the borders it's not working properly (Perhaps this was the original question?). On this i tested another simpler solution: I just changed your moveSquare function to only do work when you are inside your bounds (I mean, you shouldn't be always incrementing/decrementing position and then check if you are out of bounds to correct it).

   function moveSquare(event) {
if (event.keyCode == 37) {
if (currentPositionX > 0) {
currentPositionX -= 40;
square.style.left = currentPositionX + 'px';
}

}
if (event.keyCode == 38) {
if (currentPositionY > 0) {
currentPositionY -= 40;
square.style.top = currentPositionY + 'px';
}
}
if (event.keyCode == 39) {
if (currentPositionX < 280) {
currentPositionX += 40;
square.style.left = currentPositionX + 'px';
}
}
if (event.keyCode == 40) {
if (currentPositionY < 160) {
currentPositionY += 40;
square.style.top = currentPositionY + 'px';
}
}
}

Here is the jsfiddle: https://jsfiddle.net/epL4a9Lq/

Please, next time be more specific on your error (i would comment this before answering but i have no reputation yet for that).

Hope this helps!

move selected element with arrow keys in javascript

If I understand your question, and your desired behavior as:

Move one or more selected items, selections being made using a mouse, and moving performed via key presses, up, down, left and right.


I think you pretty much have it, the only thing, is your selections are never being cleared, which should be when any click occurs after a move has been made.

You may consider modeling the behavior in modes.

  • selection
  • move

Where the behavior, done in pseudo code would be something like this:

let mode = 0; // selection mode
let selections = [];

... key press event Listeners
... click event Listeners

function processAction( action, event ) {
If ( 'click' == action && 0 != mode ){ // was in move mode
mode = 0; // Set to selection mode.
selections = []; // resets the selections made
... // reset DOM, and clear any currently decorated elements
}

if ( 'click' == action) {
selections.push(event.targetElement);
...// Update DOM and decorate elements
}

If ( 'move' === action && mode !== 1) {
mode = 1; // This enters us into "Move" mode.
}

If ( 'move' === action ){
// Execute moving logic
}
}

To address, your "double click" issue.

Or if I double click the same element, it snaps it back to it's original position

This is the result of certain "standard" behaviors, or "presets" your browser has on how it behaves, when a user drags an element. You can disable this "standard" behavior a couple ways, one is with a little CSS

.list-item  { 
-webkit-user-drag: none;
-khtml-user-drag: none;
-moz-user-drag: none;
-o-user-drag: none;
user-drag: none;
}

You can learn more about this "default" behavior on MDN here which reads:

If this attribute is not set, its default value is auto, which means
drag behavior is the default browser behavior: only text selections,
images, and links can be dragged...


Oh and I forgot to mention, you could simply attach your event listeners to the id="list" element, as the click events of all children will bubble up and be intercepted.

You can find details on how to figure out which element was clicked here and more about how events bubble here and on MDN here specifically the section on "Bubbling and capturing explained"

PS: I've also seen in some applications, where they have similar behavior, selections being made with the mouse, and moving with the arrow keys. They allow the user to move at a different distance, when the "shift" key is being held down, while depressing an arrow key.



Related Topics



Leave a reply



Submit