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>