Use dialogs ...break that down into some functions

Here's a button.

The dialog on this page will be generated from a <template> element that is created when the page loads.

navigate my process

related content

Modal dialog content from a template

And to prove it, here's a random number: 522

The Explanation

This is one of those points where I'm maybe not exactly sure what I'm trying to do anymore, other than play with the code and try to break it down into functions. If anything I'm a little concerned I've made it more complex than it needs to be, and I'm not sure to what end. That said, I don't mind having code samples like this along the way for future reference, even if I'm not about to move it all into the library file yet.

Anyway, in any case, what I do like about this is that I've gotten rid of (in this instance) needless global variables, and the code's doing about as little as it needs to. It's not exactly parity to the previous sample, because in this case the dialog isn't be generated on demand, it's being generated on page load. I did for a bit have some logic in there to create the dialog element when the button was first clicked, but it got a little obtuse and so I simplified it to this for the sake of demonstration. (I can probably go back and generate that behavior as a future sample, though.)

I like that there's functions here with limited tasks each. The functions are passing the elements off to each other as needed. I could even, in initDialogButton, skip the declaration of dialog as a const and call up the makeDialog() function as a parameter directly, but that could be a little hard to read:

attachButtonToDialog(selector, makeDialog("#dialogTemplate", "body"));

At which point I really don't even need to use an initDialogButton() entirely—I could replace selector with my "#dialogTemplate" string directly, and call attachButtonToDialog() directly from the top level of the script—but, I mean, I don't know if that's going to be the most readable thing I could create.