The previous lesson of Javascript Lessons Series was about Html Form Validation and in this lesson we will learn about javascript keyboard events.
There are 3 types of keyboard events in javascript:
1. OnKeyPress
2. OnKeyDown
3. OnKeyUp
The above line of code will show an alert message when a keyboard key is pressed while html text box is in focus.
Another way to attach onkeypress event to an html element is to do it in javascript:
Another method of attaching onkeydown event to an html element in javascript is given below:
Another method of attaching onkeyup event to an html element in javascript is given below:
Stay tuned for more lessons...
There are 3 types of keyboard events in javascript:
1. OnKeyPress
2. OnKeyDown
3. OnKeyUp
OnKeyPress
Javascript onkeypress event is triggered when a user presses a keyboard key. There are several ways to attach onkeypress event to an html element. Let us attach onkeypress event to an html input text element.
<input type="text" onkeypress="alert('You pressed a key');" />
The above line of code will show an alert message when a keyboard key is pressed while html text box is in focus.
Another way to attach onkeypress event to an html element is to do it in javascript:
<input type="text" id="txt1" />
<script type="text/javascript">
var txt1 = document.getElementById('txt1');
txt1.onkeypress = myfunc1;
function myfunc1(){
alert('You pressed a key');
}
</script>
OnKeyDown
Javascript onkeydown event is almost similar to onkeypress event with only minor difference between the two. Just like onkeypress event, onkeydown event is triggered when a user presses a keyboard key. Example code of attaching onkeydown event to an html input text element is given below:
<input type="text" onkeydown="alert('You pressed a key');" />
Another method of attaching onkeydown event to an html element in javascript is given below:
<input type="text" id="txt1" />
<script type="text/javascript">
var txt1 = document.getElementById('txt1');
txt1.onkeydown = myfunc1;
function myfunc1(){
alert('You pressed a key');
}
</script>
OnKeyUp
Javascript onkeyup event is triggered when a user releases a keyboard key. Example code of onkeyup event attached to an html input text element is given below:
<input type="text" onkeyup="alert('You released a key');" />
Another method of attaching onkeyup event to an html element in javascript is given below:
<input type="text" id="txt1" />
<script type="text/javascript">
var txt1 = document.getElementById('txt1');
txt1.onkeyup = myfunc1;
function myfunc1(){
alert('You released a key');
}
</script>
Stay tuned for more lessons...
No comments:
Post a Comment