-1

I want call below code from HTML on event (right arrow key).

var Anim = function() {
var box = document.getElementById("square");
};
Anim.prototype.Start = function(event){
if(event.keyCode == 39){
    box.style.left = (box.offsetLeft + 100)+"px";
}
};
Anim.prototype.Stop = function(event){
if(event.keyCode == 37){
    box.style.left = (box.offsetLeft)+"px";
}
};
var Myanim = new Anim();

Here is my HTML

<div id="square" style="position: absolute;">This is my box</div>
Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
  • Your `box` variable is local to the `Anim` constructor. Your `Start` and `Stop` methods won't be able to access it. Maybe you wanted to [use a property](http://stackoverflow.com/a/13418980/1048572)? – Bergi Apr 25 '15 at 21:16

1 Answers1

0

Using jQuery :

$(document).keypress(function(event) {
   alert('Handler for .keypress() called. - ' + event.charCode);
});

To import jquery in your project :

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>

If you want to use Javascript only :

window.onkeydown = function (e) {
var code = e.keyCode ? e.keyCode : e.which;
if (code === 37) { //left key
    alert('up');
} else if (code === 40) { //down key
    alert('down');
}};
Leogout
  • 1,187
  • 1
  • 13
  • 32