How to Execute JavaScript Events Without Interacting with HTML Elements
HTML events are triggered by interacting with HTML elements,
such as by clicking on a button or by entering into an input.
However, we can actually execute the events without engaging the HTML elements. For example, we can
execute a onclick event handler of a button without clicking on the button.
<button onclick = "alert('hi')" id = "myButton">Alert</button><br><br>
<button onclick = "myButton.onclick()">Execute the Above Button</button>
Why Can We Execute An Evenet Without Engaging with the HTML Element
We can fire an event without touching the HTML element because an we can make a HTML element an obecjt and
use its methods, which include all evenet handlers available, including onclick, onmouseove, and etc..
When do I Call An Event Without Engaging the HTML Elements
I make an event executed without directly engaging with the HTML element, when I define the oninput event handler
to an input. This means when a user type in a value in the input, some functions are executed. Then, when I want to
execute these same fuctions right after the windows loads, I can just use this code.
document.getElementById('someinput').oninput();
Example of Not Execuating With HTML Element Object Method
<input oninput="show_1.innerHTML = this.value" value="example" /> <div id="show_1"></div>
Example of Execuating With HTML Element Object Method
<input id="myInput_1" oninput="show_2.innerHTML = this.value" value="example" />
<div id="show_2"></div>
<script>
document.getElementById('myInput_1').oninput();
</script>
This also works even if the oninput event hendler executes some functions that take some parameter.
<input id="myInput_2" oninput="somefunc(this)" value="example" />
<div id="show_3"></div>
<script>
function somefunc(t){
document.getElementById("show_3").innerHTML = t.value;
};
document.getElementById('myInput_2').oninput();
</script>
Comments
Post a Comment