I am new to Javascript and trying to create a Javascript click function that will display the input element when the button is clicked and hide it when the button is clicked again. My console shows no error messages but when I click the button the input element does not hide. Again I am very new to Javascript, I appreciate any feedback!
document.addEventListener("DOMContentLoaded", load);
function load() {
let button = document.querySelector("button");
button.addEventListener("click", clickMe);
}
// Click Function to change the display value of the input
function clickMe() {
let input = document.getElementById("popup");
if (input.style.display == "none") {
input.style.display = "block";
} else {
input.style.display = "none";
}
}
<!-- <form> I commented out the form element because it does not work to use .addEventListener inside form -->
<label for="button"></label>
<fieldset>
<ol>
<li><button type="button" onclick="clickMe()">Click me!</button></li>
<li><input type="text" name="popup" id="popup" placeholder="placeholder"></li>
</ol>
</fieldset>
<!-- </form> -->
>Solution :
Two things:
- You don’t need to add both the
onclickattribute and an event listener. Just use.addEventListener, it is the preferred way. - Don’t use tag selectors unless you really want to affect every
<button>element. In your case, you should use an ID, such as"clickMeBtn".
document.addEventListener("DOMContentLoaded", load);
function load() {
let button = document.querySelector("#clickMeBtn");
button.addEventListener("click", clickMe);
}
// Click Function to change the display value of the input
function clickMe() {
let popup = document.getElementById("popup");
if (popup.style.display == "none") {
popup.style.display = "block";
} else {
popup.style.display = "none";
}
}
<form>
<label for="button"></label>
<fieldset>
<ol>
<li><button type="button" id="clickMeBtn">Click me!</button></li>
<li><input type="text" id="popup" name="popup" placeholder="placeholder"></li>
</ol>
</fieldset>
</form>