Search code examples
javascriptajaxformseventspreventdefault

Javascript: why here used preventDefault?


I've been looking at some code posted by someone and I don't know why he used preventDefault here. Can anyone tell me why?

Thank you very much. https://codepen.io/Sylvia31/pen/eygvVm

form.addEventListener('submit', function (e) {

   **e.preventDefault();**

   responseContainer.innerHTML = '';
   searchedForText = searchField.value;
   const imgRequest = new XMLHttpRequest();
   imgRequest.onload = addImage;
   imgRequest.onerror = function (err) {
      requestError(err, 'image');
   };

Solution

  • You can see from the Event.preventDefault() MDN Reference that :

    preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

    And with a form the default action of clicking the submit button would be to submit the form and redirect the user to the action page defined in the form, and the use of preventDefault() in the submit event handler can stop the form submission.

    In your case e.preventDefault() is used here to stop the form default submission behavior and execute an alternative block of code, which is in this case an XMLHttpRequest.