Javascript Resetting

Hello y’all,

I’m tryin to create a dynamic list! every time I click, I see the

  • document get created for a split second and then disappear. Does anyone know why this might be happening?

    Here is my code

    const submit = document.querySelector("#submit")
    
    let ul = document.querySelector("#dynamiclist")
    
    let item = document.querySelector("item")
    
    
    const submit = document.querySelector("#submit")
    let ul = document.querySelector("#dynamiclist")
    let item = document.querySelector("item")
    
    submit.addEventListener("click", () => {
     const li = document.createElement('li')
     ul.append(li)
    })
    
  • Hi iangoodman,

    Can you show the HTML as well?

    Here it is!

    <!DOCTYPE html>
    <!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
    <!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
    <!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
    <!--[if gt IE 8]>      <html class="no-js"> <!--<![endif]-->
    <html>
      <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Celine Shopping List</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="style.css">
      </head>
      <body>
        <h1>Celine's Grocery List</h1>
        <form action="">Item: 
          <input type="text" id="item">
          <button id="submit">Submit</button>
        </form>
        <ul id="dynamiclist">
          
        </ul>
        
        <script src="index.js" async defer></script>
      </body>
    </html>
    

    Just as I thought. The button is trying to submit the form it is in which is refreshing the page. To fix this you have to stop the default action the button does. You can do this by adding an event object as a parameter to your function then calling preventDefault() on it.

    submit.addEventListener("click", (event) => {   // Here I add "event" as a parameter
        event.preventDefault();    // This stops the form submission and refresh
        const li = document.createElement('li');
        ul.append(li);
    })
    
    1 Like