Reputation: 6990
I am a bit confused how does the following works? I will post out the codes first,
html
<form>
<input type="text" id="guessInput" placeholder="A0" />
<input type="button" id="fireButton" value="Fire!" />
</form>
js
function handleFireButton(){
console.log("I am clicked");
}
function init(){
var fireButton = document.getElementById("fireButton");
fireButton.onclick = handleFireButton;
var guessInput = document.getElementById("guessInput");
guessInput.onkeypress = handleKeyPress;
}
function handleKeyPress(e){
var fireButton = document.getElementById("fireButton");
if(e.keyCode === 13){
fireButton.click();
return false;
}
}
window.onload = init;
What my question is, in it init
I can understand the first part where fireButton.onclick = handleFireButton;
this way it'll active the function when clicked but the second half is where I am bit confused.
I understand when onkeypress
it'll active the handleKeyPress
which passes the event object to check if the keyCode === 13
if so fireButton.click()
will be activated but nothing here mentioned anything about activating handleFireButton()
how does it know when fireButton.click()
it should go to the handleFireButton()
?
Upvotes: 0
Views: 123
Reputation: 11581
The click()
function fires off a click event, which is picked up by any relevant event listeners. It essentially simulates the user clicking the element.
From MDN:
The HTMLElement.click() method simulates a mouse click on an element.
When click is used with elements that support it (e.g. one of the
<input>
types listed above), it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an<a>
element to initiate navigation as if a real mouse-click had been received.
So, fireButton.click()
isn't calling handleFireButton()
directly, instead it is generating an event which the handleFireButton()
onclick event listener is reacting to.
Upvotes: 3
Reputation: 19
Do you use jquery or plain JavaScript?
For jquery you can simply call the Funktion within click
fireButton.click(funktion(){fireButton handle()})
For plain JS you have to use the onclick function
Upvotes: 0
Reputation: 66
Its the same dom element that you have in both places. You first attached an event handler to the dom button. Now u are accessing the same button from dom. And are clicking it. Since the handler is already attached it is firing the handler.
Upvotes: 1