Open/close a modal

I have a modal open up when I click the “Join Now” link


image


you can see show has been added as a class to it (id=“register”) by inpecting the element. but clcking the X does nothing
image


function register() { 
  const reg = document.querySelector('#register'); 
   reg.classList.add('show'); 
} 
function registerClose() { 
  const reg = document.querySelector('#register'); 
  reg.classList.remove('show'); 
} 

Worse yet, it dissapears (show is removed from its classes) if the mouse is clicked anywhere else, what gives?

Consider using a <dialog> element for the modal and a <button> element for the “✕”.

1 Like

What causes the modal to initially be hidden?

There must be more code that you have shown as the code above does what you would expect it to do,

Here’s the truncated version of your code showing it working.

https://codepen.io/paulobrien/pen/ZYEvVxq/42de67708b7607cab81e3af1f0b0d2b1

I would guess that you have more code that we have seen or you have not set the correct css specificity (e.g.#register{display:none} will be more specific than .show{display:block}).

Generally for modals they are designed to be dismissed if you click outside the modal (which for forms modals is not desirable) or they can usually be dismissed with the keyboard when escape is pressed. It all depends on the full code you are using.

3 Likes

Example?

Thanks, can I use the code?

You may wish to use the open attribute.

1 Like

is this better?

I was following
https://codepen.io/kevinpowell/pen/KKyOYvM
If I change the form method to dialog, how do I get to the forms input?
I can’t use

$_POST[]

You have two options:

  1. Add another form with method="dialog" that just wraps the close button
  2. Add formmethod="dialog" to the close button, which overrides the default form method when clicked

In both cases, keep your main form with method="post".

ok, is this ok?

<form method="dialog">
<button type="button">&times;</button>
</form>

then put a form with another method under it in the same dialog?

Try this:

https://codepen.io/Archibald2/pen/JojppPP

Note the dialog has a backdrop and ‘Esc’ key works…

(I am picking up a bug in Firefox: if you submit without filling in the email it shows “Manage Passwords” instead of “Please fill in this field”.)

2 Likes

Yup. :-)

Which is best then? Yours or Archibalds solution? Whats the difference?

One uses JS to close the dialog, the other uses a HTML construct. Functionally they’re pretty much equivalent.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.