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;
}
)
3
Answers
There are some different between click event and submit event. For example the submit() method waits for the DOM to load, but the click() method doesn’t. I recommend you to study about it.
I tried the following code, exactly as your code, it seems to be working perfectly.
Perhaps your page is being reset whenever you are clicking the button, which will reset and re-render your page. May be you need to look into it
Try including the attribute
type="button"
on the button element declaration in HTML.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 callsevent.stopPropagation
and/orevent.preventDefault
.