Why does my code reset when using addEventListener with "click"?

47 Views Asked by At

I'm trying to implement addEventListener so that every time I click a button a new LI will be added to my HTML with text. For some reason the LI is added for a fraction of a second and then disappears. I have implemented a form with user input similarly while listening to 'submit', but when I try to do the same with 'click' it won't work. I can use the 'submit' option but I'm trying to understand why 'click' is not working. I'd appreciate any help. Thank you!

const searchBtn = document.querySelector('#searchBtn');
const list = document.querySelector('#uls');

searchBtn.addEventListener('click', function () {
    const movieName = document.createElement('LI');
    const text = "works";
    list.append(movieName);
    movieName.innerHTML = text;  
    }
)
1

There are 1 best solutions below

0
traktor On

Try including the attribute type="button" on the button element declaration in HTML.

 <button id="searchBtn" type="button">Search</button>

This prevents the button submitting the form (which resets the page), because the default button type is "submit".

If you never want the form to be submitted, try removing the opening and closing form tags, or supply a submit event handler that calls event.stopPropagation and/or event.preventDefault.