David58
David58

Reputation: 39

Clicking my button causes the page to refresh

I just want to ask about the HTML code that why when I click, the Hello world just appear but not stay in my screen?

<!DOCTYPE HTML>
<html lang="en">

<head>
  <link href="style.css" rel="stylesheet">
  <title> Hello world</title>
</head>

<body>
  <!-- Create a button that when click alert to the screen Hello World-->
  <form>
    <button id="myBtn">Click here</button>
  </form>
  <p id="hi"></p>
  <script>
    let body = document.querySelector('body');
    document.getElementById('myBtn').addEventListener('click', function() {
      body.style.backgroundColor = 'red';
    });
  </script>
</body>

</html>

Upvotes: 3

Views: 1314

Answers (1)

Brooke Hart
Brooke Hart

Reputation: 4059

Unintuitively, the implicit type of a <button> tag is submit, not button. So when you have a <button> element without a type attribute inside a <form> element it will cause that form to submit. In this case, your form is lacking an action attribute so it will default to submitting to the page you are currently on, which will cause your page to reload.

In this case, the problem is easily resolved by removing the <form> tag, because it's not needed for any other reason. But more generally, I would recommend adding a type="button" attribute on any <button> element that isn't intended to be used to submit a form.

Even if you know in some cases that your button isn't inside a form, it's a useful habit to get into. In some large projects, you might be writing isolated bits of HTML that will get inserted into various contexts, so type="button" can prevent bugs from occurring if you create a button in isolation that later gets inserted within a form for some reason.

For completeness, you also have the option of capturing the submit event as the first argument of your event handler, and preventing its default action with the preventDefault method:

<!DOCTYPE HTML>
<html lang="en">

<head>
  <link href="style.css" rel="stylesheet">
  <title> Hello world</title>
</head>

<body>
  <!-- Create a button that when click alert to the screen Hello World-->
  <form>
    <button id="myBtn">Click here</button>
  </form>
  <p id="hi"></p>
  <script>
    let body = document.querySelector('body');
    document.getElementById('myBtn').addEventListener('click', function(e) {
      e.preventDefault();
      body.style.backgroundColor = 'red';
    });
  </script>
</body>

</html>

This would prevent default action of the submit event, so the page wouldn't reload even though you clicked a submit button. But because the form element in this case isn't needed for any other reason, it makes more sense to just remove it.

Upvotes: 5

Related Questions