How to stop the movement of the object when the button is released?

<div class="player">
 <!-- Character -->
</div>


.player {
 border: 1px solid black;
 width: 6%;
 height: 17.3%;
 background: url(img/start.png) no-repeat;
 position: absolute;
 bottom: 15%;
 left: 68%;
 /*left: 46%;*/
 z-index: 3;
 transition: bottom .20s ease-in-out, left .5s linear;
}


document.onkeydown = function(e) { 

 if (e.keyCode == 37) {
 posX = document.querySelector('.player').offsetLeft;
 xn = posX - 150; 
 document.querySelector('.player').style.left = xn + 'px';
}

}

document.onkeyup = function(e) {

 if (e.keyCode == 37) {
 // What here to write???
}

}


What you need to add in the onkeyup to the object is immediately stopped when you release the button? At the moment, when I hold and then release the mouse button, the object continues to move at 150px
March 19th 20 at 08:33
2 answers
March 19th 20 at 08:35
you change animations need to hang on the timer type set the time out and add distance little by little, and pressed to cancel the timer to stop on the last level
and can as an example. I'm just where the timer did not try and did not work - mariana.Wintheiser63 commented on March 19th 20 at 08:38
document.onkeydown = function(e) { 

 if (e.keyCode == 37) {
 posX = document.querySelector('.player').offsetLeft;
 xn = posX - 50; 
 var timerId = setTimeout(function() {
 document.querySelector('.player').style.left = xn + 'px';
 }, 0);
}

}

document.onkeyup = function(e) {

 if (e.keyCode == 37) {
clearTimeout(timerId);
}

}

so? - mariana.Wintheiser63 commented on March 19th 20 at 08:41
@mariana.Wintheiser63, jquery animate/stop look how it works. - Elbert50 commented on March 19th 20 at 08:44
@mariana.Wintheiser63, Transfer example https://jsfiddle.net/ I'll correct it - Elbert50 commented on March 19th 20 at 08:47
@Elbert50, And I JQuery I do not know - mariana.Wintheiser63 commented on March 19th 20 at 08:50
I would be in pure JS - mariana.Wintheiser63 commented on March 19th 20 at 08:53
https://jsfiddle.net/o91bce6w/ - mariana.Wintheiser63 commented on March 19th 20 at 08:56
@mariana.Wintheiser63, https://jsfiddle.net/tnh9ja1m/ - Elbert50 commented on March 19th 20 at 08:59
@mariana.Wintheiser63, https://learn.javascript.ru/js-animation - Elbert50 commented on March 19th 20 at 09:02
March 19th 20 at 08:37
Nothing should stop because it will stop. The cause of your problem is that you nerovnosti, and each time the event is triggered, you're rocking the element from the dom, and you have in the beginning only to make a link to it, and work with it.

Find more questions by tags HTMLJavaScriptCSS