I am not able to understand the parameter 'e' which is passed to prevent the Default Action in JavaScript:
document.getElementById('submit').addEventListener('click', calculate, false);
function calculate(e){
e.preventDefault():
}
I am not able to understand the parameter 'e' which is passed to prevent the Default Action in JavaScript:
document.getElementById('submit').addEventListener('click', calculate, false);
function calculate(e){
e.preventDefault():
}
The e in e.preventDefault prevents the default action when a link is clicked, which is the page refreshing or changing. So it allows for behavior such as clicking on a link making a call to the database without a page refresh.
Here is a guide on the topic: jQuery event.preventDefault() Method
The Event
type is passed into the second argument of addEventListener. This is referenced as e
in the closure you've defined, and on which you've called .preventDefault.
MDN (in the links above) provides excellent documentation of the above type, the functions that you can call on it and the impacts those functions have.
Where the code says
document.getElementById('submit').addEventListener('click', calculate, false);
This means that the function named calculate
will be used to handle 'click'
events for the 'submit'
element in the document
. That is: the Javascript engine makes a note to call calculate
any time that the user clicks on the element with an ID of 'submit'
.
When that function is called, it will be passed an object that represents the event - specifically, it will be a mouse event, because clicking is done using the mouse.
So, where the code says
function calculate(e){
e.preventDefault();
}
This MouseEvent
object will be assigned to the parameter e
used in the function's code. The name e
is entirely arbitrary, just like any other function parameter. The object stores a lot of information about the event: for example, which buttons were clicked, whether modifier keys were pressed for the click, the location of the click (in multiple different coordinate systems), and whether it came from an actual mouse or from touching a touchscreen. It also provides the core Event
functionality, such as a timestamp for exactly when the mouse was clicked.
For completeness:
Any time that the mouse is clicked in the browser normally, the browser itself will have its own rules for what should happen - for example, clicking on an ordinary <a>
link tells the browser to go to the linked URL. This is the "default" action. The Event
has a special method preventDefault
: calling this method signals to the browser to prevent that default action - i.e., to not do whatever it was going to do otherwise.
This is useful so that, for example, a submit button on a form can do some validation in Javascript, and then not submit the form if there is something wrong with the form inputs.