0

So when users click the button, I want the first section to disappear, and the second section to show. What's happening here is like a flash. The first section just hides for a second, so does the second. Please take a look at code my code :)

HTML

 <style>
        .hide{
            display: none;
        }
 </style>


 <section id="first">
            <form>
                <label for="p1Name">PLAYER ONE</label>
                <input type="text" id="p1Name" placeholder="TYPE PLAYER NAME">
                <label class="label" for="p2Name">PLAYER TWO</label>
                <input type="text" id="p2Name" placeholder="TYPE PLAYER NAME">
                <button id="start">START</button>
            </form>
        </section>
        <section id="second" class="hide">
            <h1>HELLO, WORLD!!!</h1>
        </section>

Javascript

const button = document.querySelector("#start");
const firstPage = document.querySelector("#first");
const secondPage = document.querySelector("#second");

    button.addEventListener('click', ()=>{
        firstPage.classList.add("hide");
        secondPage.classList.remove("hide");
        console.log("work");       
    })
WYZku
  • 3
  • 3
  • 1
    The default action for a ` – Andreas Sep 10 '21 at 08:35

1 Answers1

1

The default type of a button is submit, as a result the form is submitting when clicking the button. You can either explicitly set the type of the button to button or you can prevent the event inside the click event handler function using preventDefault() to stay on the page.

const button = document.querySelector("#start");
const firstPage = document.querySelector("#first");
const secondPage = document.querySelector("#second");

button.addEventListener('click', (e)=>{
    firstPage.classList.add("hide");
    secondPage.classList.remove("hide");
    console.log("work");
    e.preventDefault();
})
<style>
.hide{
    display: none;
}
</style>


<section id="first">
    <form>
        <label for="p1Name">PLAYER ONE</label>
        <input type="text" id="p1Name" placeholder="TYPE PLAYER NAME">
        <label class="label" for="p2Name">PLAYER TWO</label>
        <input type="text" id="p2Name" placeholder="TYPE PLAYER NAME">
        <button id="start">START</button>
    </form>
</section>
<section id="second" class="hide">
    <h1>HELLO, WORLD!!!</h1>
</section>
Mamun
  • 66,969
  • 9
  • 47
  • 59