the purpose of this code is to add an article at the end of the page, but the broblem is that appear then it desappear

Tags: , ,



the purpose of this code is to add an article at the end of the page, but the broblem is that appear then it desappear.please help me to figur it out 🙂

        const button = document.getElementById("buttad");

        function addNewArticle() {
            const fragment = document.createDocumentFragment();
            
            const header = document.createElement("p");
            header.textContent ="Ferhane riyadh ";
            const text = document.createElement("p");
            text.textContent ="Ferhane riyadh ";

            fragment.appendChild(header);
            fragment.appendChild(text);

            document.body.appendChild(fragment);
        }
            button.addEventListener("click", addNewArticle);
  <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <meta http-equiv="X-UA-Compatible" content="ie=edge">
     <title>adding articles</title>
 </head>
 <body>
     <div>
       <form>
        <input type="text" name="title" id="title" placeholder="TAP YOUR TITLE" style="display:block; margin-bottom: 5px; margin-left:8px;">
        <input type="text" name="description" id="description" placeholder="DESCRIPTION" style="display:block;  margin-left:8px;">
        <button id="buttad" style="padding:3px; position:absolute; left:12%; margin-top:12px; background-color: black; color: white; outline: none; border: black 1px solid; cursor: pointer  ">ADD</button>
    </form>  
     </div>
    
 </body>
 </html>

Answer

This is because you are using a form without preventing the submit of it. There is no need for the form here, and by default it will submit to the same page it’s on, causing a window reload.

This has been discussed here: How to prevent form from being submitted?



Source: stackoverflow