I am trying to show a modal after an if statement is true, in my example I am doing this after the user presses Enter, in my real code there are a few other if statements nested into that one.
I wrote this codepen to illustrate the issue, and I am also putting the code here for clarity.
This is my HTML, pretty basic, creating the dialog and not providing the "open" attribute, so it’s hidden by default:
Press Enter
<dialog id="greeting">
<p>Greetings, one and all!<p>
<form method="dialog">
<button>×</button>
</form>
</dialog>
Then we have the Javascript where I grab the modal and store it in a global variable, create a function listening for pressed keys and another one that parses them. Inside the parsing function, I added the code to (unsuccessfully) show the model only if the pressed key is "ENTER".
let greeting = document.getElementById("greeting");
window.addEventListener("keydown", function (e) {
parseKey(e.key);
});
function parseKey(pressedKey) {
pressedKey = pressedKey.toUpperCase()
if (pressedKey== "ENTER") {
console.log(greeting);
greeting.showModal();
console.log(greeting.getAttribute("open"));
//greeting.setAttribute("open", "open");
//alternative = document.getElementById("greeting");
//console.log(alternative);
//alternative.showModal();
}
}
As you can see, I also:
- Used
console.log()as a sort of debugging tool to make sure the if statement worked and that the modal was actually available inside the function. That seems to work, so when I press Enter, the console shows the HTML code of the modal - Logging the value of the "open" attribute for the modal, getting an empty string as a response
In the commented out part I also tried:
- To set the attribute manually
- To grab the modal directly inside the function, once again getting the same result of the function logging to the console the HTML of the modal, but the modal remaining hidden
When I tried putting two showModal() one after the other, I got the InvalidStateError: HTMLDialogElement.showModal: Dialog element already has an 'open' attribute, which makes me think I am clearly missing something, since the modal is still invisible.
Thanks to everybody that can help.
>Solution :
you need to prevent the native event to be executed.
Add e.preventDefault(); and everything should work fine.