what does event.preventDefault(); do

·

2 min read

While developing a simple program to convert temperatures from Fahrenheit to Celsius, I encountered a certain piece of code that prompted me to delve deeper into its functionality.

event.preventDefault();

In the context of a web form, the default behaviour of a 'submit' event is to send the form's data to the URL specified in the form's action attribute (or to the current URL if no action is specified). The form data is packaged and sent to the server in a format determined by the method attribute (either GET or POST).

However, when creating web applications, developers often want to handle form submissions using JavaScript rather than by directly sending the data to a server. This approach offers several advantages, such as client-side data validation, asynchronous data submission (using AJAX or Fetch API), or even just enhancing user experience by not causing a page reload.

JavaScript's Event interface provides a method called preventDefault() that, when invoked, cancels the event if it is cancelable, meaning the default action that belongs to the event will not occur. For the 'submit' event of a form, the default action is to send the form's data to the server and then refresh the page. By calling preventDefault() in the 'submit' event listener, these default actions are cancelled.
So when you use event.preventDefault() inside a form's submit event listener like this:

document.getElementById('tempForm').addEventListener('submit', function(event) {
  // Prevent form from submitting normally
  event.preventDefault();

  // Get the Fahrenheit temperature from the input field
  var fahrenheit = document.getElementById('fahrenheit').value;

  // Convert it to Celsius
  var celsius = (fahrenheit - 32) * (5/9);

  // Show the result
  alert(fahrenheit + ' degrees Fahrenheit is ' + celsius.toFixed(2) + ' degrees Celsius.');
});

The form's 'submit' event is being listened for, and when the event occurs (when you click the submit button on the form), the function is executed. Inside this function, event.preventDefault(); is called, which stops the browser from making the default form submission (i.e., sending a request to the server and refreshing the page).

After event.preventDefault(); is called, the rest of the function can run, which in this case, takes the value from the input field, performs the temperature conversion, and shows the result in an alert dialogue. Because the default form submission behaviour was prevented, the page does not refresh, allowing for a smoother user experience.