0

I have an idea to create an object Shout, which should take keyboard messages onkeypress event from the input element. When the user presses a key, there should appear alert box with shout exclamation.

The problem arises, when I want to access object properties inside the new onkeypress function, because keyword this refers to the input element itself and not to the Shout object.

Is there any way how to work around it?

I am not sure, if this concept is optimal, but I take it like an experiment.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>main</title>

</head>
<script>
var Shout;

function ShoutObj(_shout){
    this.shout = _shout;
    this.onkeypress = function(event){
               alert(this.shout); // shout is undefined, because "this" refers to input element
        }
}


function DoItFirst(){
    var selector = document.getElementById("s1");
    Shout = new ShoutObj("ouch");
    selector.onkeypress = Shout.onkeypress;
}

</script>

<body onload="DoItFirst()">
  <input id="s1" type="text"/>
</body>
</html>
lyborko
  • 2,571
  • 3
  • 26
  • 54
  • You don't have to create an object to bind functionality . 2nd : just create a function that alerts shout --> function shout(){alert()} – KpTheConstructor Mar 25 '16 at 13:19
  • @KpTheConstructor: thanks, but I have seen solution in the proposed duplicate. Here it it sufficient add: o = this; this.onkeypress = function(event){ alert(o.shout); } – lyborko Mar 25 '16 at 16:18

0 Answers0