Categories
JavaScript Answers

How to stop reloading page with Enter Key with JavaScript?

Spread the love

Sometimes, we want to stop reloading page with Enter Key with JavaScript.

In this article, we’ll look at how to stop reloading page with Enter Key with JavaScript.

How to stop reloading page with Enter Key with JavaScript?

To stop reloading page with Enter Key with JavaScript, we call preventDefault.

For instance, we write

document.getElementById("searchForm").addEventListener(
  "submit",
  (e) => {
    e.preventDefault();
    search(document.getElementById("searchText"));
  },
  false
);

to select the form with getElementById.

Then we call addEventListener to add an event listener for the submit event.

We use a function that calls preventDefault to stop the default submit behavior to stop the page reloading.

And then we call search with the field with the search text we get from getElementById.

Conclusion

To stop reloading page with Enter Key with JavaScript, we call preventDefault.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *