Execute Other Events With Keyboard Events

When users use a webapp or browse a website. They sometimes want to use the keyboard to do somehitng, such as pressing "enter" to submit a form or press "esc" to escape some actions
How to find all the key code? Check out this article.
For exampe, if wa want to clear an input box with pressing the "eac" key.
Type in the input box then press "esc" key to see the effect.
<input id="myInput" />
<script>
window.onkeydown = () =>{
	if(event.keyCode == 27){
		myInput.value = "";		
	};
};
</script>

Fire an Event

If we want to fire an event with a press on a key, we just assign functions to that keycode

But if the rvent which is already listened by an HTML element such as a button and the event consists of many functions. In order to make our code more manageble, we can just use the element object and call the method corresponding to the event listener

For example, if we want to do exact the same thing with pressing "enter" as clicking on a button, where the button triggers a set of functions

Wrting same code twice.

<button id="myButton" onclick="somefunction_1();somefunction_2()">Submit</button>
<div id="showMessage"></div>
<script>
function somefunction_1(){
	showMessage.innerHTML = 'Hi';
};

function somefunction_2(){
	showMessage.innerHTML += ' and hello.'
};

window.onkeydown = () =>{
	if(event.keyCode == 13){
    	somefunction_1();
        somefunction_2();
   };
};
</script>

Wrting same code once.

<button id="myButton" onclick="somefunction_1();somefunction_2()">Submit</button>
<div id="showMessage"></div>
<script>
function somefunction_1(){
	showMessage.innerHTML = 'Hi';
};

function somefunction_2(){
	showMessage.innerHTML += ' and hello.'
};

window.onkeydown = () =>{
	if(event.keyCode == 13){
		myButton.onclick();
   };
};
</script>
Here, one interesting thing is that we can also fire events even if the HTML element can not fire under normal conditions, such as div tag can't fire onfocus event.

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser