0

This code was meant to change the innerHTML from 'login' to 'changed' but when I click on the button, the changes work for only a second and changed back to 'login'

please check if I'm doing anything wrong

the html code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script
            src="https://kit.fontawesome.com/64d58efce2.js"
            crossorigin="anonymous"
    ></script>
    <script src="script.js" type="text/javascript" defer></script>
    <link rel="stylesheet" href="style.css" />
    <title>Sign in & Sign up Form</title>
</head>
<body>

</body>
</html>

the javascript code

const main = document.createElement("main")
main.classList.add("foo", "bar")
main.innerHTML =`
<form action="" class="sign-in-form">
    <h2 class="title">Sign in</h2>
    <div class="input-field">
        <i class="fas fa-user"></i>
        <input type="text" placeholder="Username"/>
    </div>
    <div class="input-field">
        <i class="fas fa-lock"></i>
        <input type="password" placeholder="Password"/>
    </div>
    <button type="submit" class="btn solid">Login</button>
    <p class="social-text">Or Sign in with social platforms</p>
</form>
`

document.querySelector("body").append(main)
const button = document.querySelector(".btn")
button.addEventListener("click", (event)=>{
    event.preventDefault();
    button.innerHTML = "changed"
})

1 Answers1

0

You can pass a event to your function and use event.preventDefault() to stop the submission. Otherwise, it will reload the page.

const button = document.querySelector(".btn");
button.addEventListener("click", event => {
  event.preventDefault();
  button.innerHTML = "changed";
});
<body>
    <form action="" class="sign-in-form">
      <h2 class="title">Sign in</h2>
      <div class="input-field">
        <i class="fas fa-user"></i>
        <input type="text" placeholder="Username" />
      </div>
      <div class="input-field">
        <i class="fas fa-lock"></i>
        <input type="password" placeholder="Password" />
      </div>
      <button type="submit" class="btn solid">Login</button>
      <p class="social-text">Or Sign in with social platforms</p>
    </form>
  </body>
ikhvjs
  • 5,316
  • 2
  • 13
  • 36
  • @ChidimmaNworah, try to understand why it works instead. You may actually need to submit the form after validation of the input field. So, the ```event.preventDefault()``` may be only for invalid validation in your case. – ikhvjs Jun 18 '21 at 10:29
  • yes I'll get there, I'm a newbie and trying to test how the eventlistener works – Chidimma Nworah Jun 18 '21 at 10:35