This dialog element is amazing not just for accessibility but it comes with its own show/close API that can be easily implemented in React with a useRef hook. This should be the direction for web/mobile app development - making life easier for both the end user and developer.
It's long overdue. There have been far too many hacky ways of doing things in the frontend, these things should just exist by default. I wish the details element could receive a bit more love.
One of the big advantages of a platform such as this is that many teaching styles are available, and you can find those which suit your learning style the best. That's one thing that neither college nor work will necessarily make so readily accessible.
Wow, I remember implementing modals like that 11-12 years ago for my pet projects back in the times when I studied at school. So surprised that only now it became a standard feature
The best feature imho are stacked modals. If you try to create a modal inside a modal the old fashioned way with the outer modal(overflow:hidden), it will display the stacked (inner) modal only inside the already opened modal. With you're completely free to stack and overflow as you like.
@@encycl07pedia- it is excellent way to provide a sub-par interface. And the “easiest” way is to provide a confirmation to some action inside a modal. Users will then know that you study (low) quality UI.
Just a small tip. At least on VSCode, do you know that you can change the element's tag name more easily ? Click on the tag name then press F2. It avoids having to modify the name on the closing or opening tag because it works both ways.
8:41 I've been familiar with modals for over a year, but it wasn't until I watched your video that I discovered the save form inputs feature doesn't require JS. That's a fantastic revelation! 7:50 I have a small tip for those who declare global CSS variables using :root{}. Keep in mind that you cannot apply them to the backdrop because they are considered 'undefined' within the same module level as the :root{} and they're considered out of scope
I always watch Kyle's videos before I sleep... This time I dozed off with my hand on the phone's keyboard. Sorry for the emoji spam lol Spent 10 minutes deleting emojis here
They always seemed relatively straightforward to me when using a css/js framework like Bootstrap, but at least now it should be even simpler since it's becoming a base feature of HTML5.
Pretty neat. I like that it's allowing to close with the escape key by default. It would be a bit cleaner to wrap the contents of the dialog rather than using coordinates on click though. Then it's just : `dialog.addEventListener('click', e => e.target !== wrapper && dialog.close())`
Your code would close the dialog when user clicks on another element inside the wrapper. The condition should rather use the contains method: `wrapper.contains(e.target)`
@@Grouiiiiik or you can do this: wrapper.addEventListener( "click", (e) => e.stopPropagation() ); dialog.addEventListener( "click", () => dialog.close() );
Rather than introduce complexity with getBoundingClientRect (which may potentially trigger all kinds of false positives from dropdown menus, rounded corners, and other dialog interaction that may overflow the cursor rectangle target), why not simply wrap the content inside the dialog with a div and set an event listener that closes the dialog when that content wrapper div loses focus? In fact, I wonder if the dialog object itself might not also raise a blur event somewhere that we can detect and handle. Awesome video, in any case, Kyle.
Yeah, even without the div, seems like it should be possible to get the actual target in the bubbling phase and compare selector to check if it is the backdrop element or not.
@@dsego84 As a result of this discussion, I've been toying around with this in CodePen and have not been able to trap the actual target natively. The main problem is that the full page backdrop is part of the modal. In effect, when the modal is open, all clicks all over the page are regarded by the DOM to still be inside the modal. In practice, there is no way for the modal to lose focus at runtime while open. The div trick works. It's a decent workaround (a better workaround than getBoundingClientRect in my opinion) but it's not perfect. The div style must be forced edge to edge to occupy the entire dialog. If you don't do that, a click on any whitespace inside the dialog but outside the div counts as a blur event and the dialog closes. I now share Kyle's frustration, all of these tricks should be future polyfill. Truth is, the dialog object itself should natively raise an event when the backdrop is clicked. Even easier, I'd love a property we could simply set to change the modal behavior to make it close on such a click. Frankly, if we are making a wish list, I'd like both. In fact, I'd also like the backdrop to be a property of the dialog object instead of a pseudo style. My current assessment is the dialog tag is a big improvement on the usual hassles with modals but the implementation is only about 90% there. I'm still experimenting to find a universal elegant solution for modal close-on- blur. My gut still tells me that something else somewhere must bubble to the DOM that we can use as a trigger.
@@robertholtz Wow, thanks for poking around. Agreed the div trick is a decent workaround. Too bad it's not possible to trap the target natively. Thanks for the write-up as well!
@@krzysztofrozbicki1776 You are quite right. I pointed that out later in the thread when I started actually testing this out. You must override dialog's default styling and make sure your control div spans edge-to-edge of the entire dialog. Any click on the whitespace inside the dialog but outside the div counts as a trigger and the dialog closes. I'm still looking for a more elegant solution but I believe this is still better than getBoundingClientRect. With the div approach, not overriding the default dialog padding is the only way I have found that may raise a false positive but that has an easy fix. In contrast, getBoundingClientRect has many potential false positive scenarios, some of which are so involved to guard against that it nets out to be far less work to just do modals the traditional way. I prefer modals that close on blur and I want to take advantage of dialog's baked-in behavior. The div trick enables developers like me to achieve both. My quest continues for a still-better detection method.
Other way to handle click outside is to listen on click for dialog element and, add `e.stopPropogation` for dialog body. This can also handle the edge case when border is rounded.
Thanks for bringing this to people's attention👏. I am currently "migrating" from A11yDialog (which is great btw) to native, now that implementations got so much better over the last couple of years. Also saves so much custom and library code all over: HTML, CSS, JS; from several kb to a few dozen lines all across.
Man you realy save me, i was using the dialog modal but in react and doing preventDefault() doesn't work very well, but now i understand why, thanks a lot!!
I like the way you explain things. I came from express video and the way you explain things and giving people some really nice tips or feature that I don't even know exist. Keep doing it man!
Finally, something! I still don't understand why for so many years HTML doesn't have such simple features like population of or / with an array. Or even to populate a table you need to create elements or deal with strings and innerHTML
You're talking about logic there. HTML is simply a container, it has no concept of logic. For logic we use JS, or, to build on that you could use something like JSX.
But you *are* populating with an array... of elements. Markup is markup, the only way to represent data structures or anything else in it is with elements.
Great video! I was already aware of but you explained some features that make it worth using (especially the keyboard accessibility with modal dialogs). Previously I didn't see any point using this instead of JS implementation I already had implemented.
Native HTML/CSS is always preferred to a Javascript implementation, in my opinion. Though I'm a particularly biased developer that has NoScript always on by default.
I'm not gonna lie. I had to look into this and it's been supported for quite a while. How has this not been the top response for anytime someone is asking on how to make modals/dialogues?
Thanks for this and the YT algorithm for showing it to me at the right time (even if it creeps me out that it knows...) . This would be perfect for HTML/JS games to display dialog and menu screens.
You should go read the HTML docs. A lot of native elements have been introduced over the years. Dialog elements have been around for a few years already, just not widely known
I am not 100% sure why this is in my suggestion feed, but I am not complaining. Being a hobbyist coder and no one ever hiring me, making me use HTML on a daily basis, a lot of this is stuck in reference books and code example snippets. I wish I could keep this in my head more. I am amazed at how HTML has changed since the days in high school when I would make pages for my old GeoCities site. Things have sure changed.
When I clicked, I was hoping this was a video showing how the world had reinstated the synchronous modal which was removed after IE 5.5, the showModalDialog(url) method... it was synchronous just like confirm(message). Confirm() can only show a text-message and return OK/Cancel, but showModalDialog() could show and return whatever you wanted. And you could have your code in one place without needing to scatter it among callback methods and global variables... But, as always - great video!
Seems not. Tried to apply (.modal[open]) opacity or simply background color transition, but it didn't work. Even if it would work with appearing, it won't with disappearing anyway. To use benefits of dialog element and animate you will have to add and remove to dialog class with animation styles.
The dialog element adds some CSS by default, if you want to use flexbox and add display: flex to your .modal css class your modal will be visible on the page before clicking on the button. The only solution I've found is toggle a class who add display: flex when clicking on open and close buttons.... Idk if a cleaner solution exist...
That's awesome. And if you can guarantee that all of your visitors have browsers released March 2022 or later (that's when Firefox introduced support), you can actually use this. Otherwise, you'll be implementing that dialog twice.
The dialog implementation is indeed awesome, but for general use you'll have to wait until at least 2025. We still get issues reported relating to features that became available in 2020 - a customer using an outdated iOS version as a test device is not uncommon and I know from my private surroundings that a horrifying amount of people somehow use outdated software even when updates are available. At least we don't have to struggle with Internet Explorer anymore. :)
I've seen your blog website and it's awesome. But I hope you would add some basic features to it, like a "Back to Top" button on the individual blog page, a sidebar containing the table of contents on the individual blog page so that the user would be able to jump to the content they want to read, a comment section below the blogs, etc.
Pretty amazing GUI development indeed, we now have one of the ONE-LINER basic elements introduced WAAAY back in 16-bit Windows some 30 years ago. Today, we can all rejoice that even the amateurs running online banking, e-commerce or government portals are able to reliably and portably (within a VERY narrow definiton of portability. even my fridge is portable, kind of) create dialogs that may some day bring their customers a more grown-up experience if they can resist perverting the experience, LIKE YOU, DEAR SIR, JUST DID in the end of an otherwise informative video. What? "I want to exit a modal dialogue by clicking outside of it"? Because others do that? Because of never having used any real software except a web browser? Monkey see monkey do? How anticlimactic. This is why we can't have NICE THINGS, even when the holy V̶a̶t̶i̶c̶a̶n̶W3C sends us new gospel, people can't help but turn it into crap and spray it around at NVMe speeds. With the best of intentions, of course. Boy... Question: when the end user closes a dialog by clicking outside of it's borders, WHAT IS THE EXPECTED ACTION? Ok, Agree, Cancel, Save and exit? Yes? No? Quit, burn house and kill all the newborn? There is A REASON why there is no such functionality. It is BECAUSE. Think about that, please. Can ideas of aesthetics, usability, webdev BDE and (last but def not least) keeping users out of asylums coexist? Can I ever talk about calm computing without being as far as calmness as possible? Yes we can (hope I can, too) Can't get WIN16 API and MessageBox(NULL,"To be or not to be?","I am a dialog title",MB_QUESTION|MB_YESNO|MB_APPLMODAL); back, thank god, but I have to say that it is getting tired to watch people foaming at the mouth year after year when collective stupiditiy has again invented some ancient wheel again, less efficiently this time,because YES, WE CAN (make everybody and their cat eat our DOG food. and the only version that is good enough is the next version, and energy and Moore's law is a universal constant proven by scientist, right?). So, showing the dialog requires now a more complex, diverse and delicate system software compared to Windows 3, but also a BROWSER (not much of a choice since there's just rebranded Chromiums and Firefoxen left because developers have to still develop the development like there's nothing better to work on than breaking other people's stuff without warning. When are they going to freeze the features and move on to to coding something useful instead of bloating and regressing their bugridden compulsory software monsters, that are A MISSION CRITICAL PLATFORM for many and have upgrade nagging, have sandboxes and crashpads farting inside my process table wasting my precious memory and still not preventing crashes, just showing useless iconography. And is "ERR_NAME_NOT_RESOLVED" really the best way a big company like Google can explain a dns failure to their users?) too and takes at least a gigabyte of scaffolding around it (I DO NOT OWN A TURING MACHINE AS IT IS SUPPOSED TO HAVE INFINITE SYMBOLS. I have finite RAM on my system) to render even the ugliest non-movable non-END-USER-stylable slab of pixels with a button -- not looking like a button -- THAT'S GREAT! since it "works even better than what modals had before" (a modal failing in modality is... well. ununderstandably bad. no excuse for nerds there. I want to puke.)". Clearly, Sir, you are wrong. Maybe that is the cost of having the blessing of not ever writing actual desktop programs for a native development environment. Let's do the time warp again!
@@janimakinen1455 modals are the single most unnecessary / easily abused / aggravating UI element in the set of all UI elements. If you are using a modal then your UX skills are woefully inadequate and you are abusing the user.
@@aarondcmedia9585 Modals have their use, for example in the case of a CRUD web app, to prevent users from accidentally losing their progress, showing a modal when the app is in a dirty state and about to be closed is a good thing to have.
@@DesignThinkerer I disagree completely. Autosave the data as it changes. When they close the form it doesn't matter, you already saved it. When they return to the form, you can repopulate it automatically, or let them choose to repopulate from their last visit. This is like UX 101. Interrupting a user who is doing something is about as bad as UX gets. I would prefer to not treat my users like idiots who don't know what they are doing, and if they are completely new, I would prefer to make it a frictionless experience.
@@aarondcmedia9585 I agree with you, at least to a point. I hate modals personally. I'm also much more of a fan of server-side action instead of putting the entire weight of the site on the user's end.
I figured out dialog element a few months ago and I got very astonished! This is a very good tool to make modals. I only got sad with the fact of that it is not possible natively to close the modal by clicking outside it (clicking in the ::background space), and although they recommend the getBoundingClienteRect() function, it doesn't work correctly when your modal has border-radius and you click on that specifcly space. But I think it's going to get better in the future.
Aw, this makes me want to build a website again... They're making it easier bit by bit. Less hacking needed to do what our clients have thought were normal features all along.
@10:10 Click on backgrop to close modal only happens on the web. No OS I know of does this. We have added unnecessary complexity and trained the users to expect an anti-pattern to work. So finally, modals behave like they should. And yet, I bet every web dev is going to have to add the JS for click outside modal to close because the boss/customer want's to have it like this. Why is there no tag attribute or at least a JS property like open or returnValue to configure this? Why W3C? WHY?
I only wish I knew about this sooner. I spent a fair amount of time creating dialog boxes for my current project using Firefox for testing. I solved all the problems of backdrop, tab navigation, etc. BUT unfortunately when I run my code on Chrome I get annoying flashes that are completely unacceptable and will have to be fixed. I've known about this problem for months and was thinking that maybe the dialog element would be the solution, but hadn't yet found time to investigate. So now you've convinced me the dialog element is the way to go.
Amazing information once again, Kyle! Thank you. 👍 There's one single thing that I wish was covered, but perhaps it was left out due to the complexity involved. I'm developing in React and most of our applications require way more complexity of handling modals than a single one per page or application. How would this work with multiple modals being triggered from the same location? Not overlapping, obviously, but perhaps I have an extremely custom layout with multiple flows that can be triggered from the same location. I do believe you'd eventually dig into unique identifiers, but I'm just wondering if it has support for that at all. Nonetheless, gold information right here. We can finally start dropping libraries handling stuff like this. Will dive into how this could be implemented in React with Redux perhaps or with programatically triggering these modals. Much appreciated!
Great video. Thank you. I suggest for next video a practice about a carousel of images and modal window show us the image. When user click on the image , image pop up and and the other images fade.
Nice work! If you wrap up your dialog with a promise 'return new Promise(resolve => { // dialog const dialog = document.createElement("dialog")' then you need to capture the cancel event ' dialog.addEventListener("cancel", e => { resolve("cancel") })' and finally add a call to resolve to your click event handler '...dialog.close() resolve("cancel")..."
The problem with the closing dialog approach is that if you add a HTML range input selector it'll automatically close the dialog/modal even if the selection is within it.
great post, wasn't aware of this. also, I'm concerned about your second guitar leaning on the stand.. too many headstocks have broken that way (once to me!) so please be careful! haha
I'm not sure if it's still best practice, but I like to use a link styled as a button to cancel/close, and an actual button for save/submit so the cancel button can't be the default behavior if you hit enter inside an input in the form.
That is a real nice introduction to the dialog element! I was aware of it, but did not dive into details until now. Since I was a little set back by the whole "getBoundingClientRect"-thing, I prodded a little bit around. Although you can not distinguish between Dialog and Backdrop on click, you can, however, get rid of the "getBoundingClientRect". The PointerEvent has "offsetX/Y" properties which are negative when the click is left of or above the dialog. Further "offsetX > modal.offsetWidth" holds for clicks right of the dialog and conversely "offsetY > modal.offsetHeight" for clicks below the dialog. I do not know, however, if this still holds for very big dialogs - still could, I guess.
There is a bug in your clicking outside detection. If you have an element that overflows the modal, let's say a dropdown menu, and click on an option outside of the modal bounds, it will close the modal.
The dialog element is great, but unusable really for Route based modal experiences using SSR frameworks - just the one downside to look out for. Great video!
The cancel button was still of type="submit" so it did exactly that: submitting the form. A type="button" doesn't. Web Standards 😉 There are several native button types in HTML with useful default behaviours since ever. It's worthwhile learning HTML fundamentals to save yourselves the energy recreating what's already in the browser. Many devs and designers believe they are doing a better/smarter job reinventing wheels, when all they do is creating another flat. Just because the native HTML select dropdown (still) sucks, doesn't mean the other controls and elements a shit, too. Learn to use them and what they're for. Save yourselves a lot of coding and your users a big dump of pointless code they have to download for an often worse experience.
I wonder how much HTML this guy actually knows, lol 😅 I've had brain farts where I'm just "... oh" and change from input to button or something but jeez
Yes but it submits the form using the dialog method, which means it closes the dialog. Exactly what we need. According to mdn the dialog method does not submit any data, it only saves the data and closes the dialog.
Great post! Regarding your final comments... The reason it doesn't allow you to click outside to dismiss the modal is because all that area is supposed to be inert. By working around that, you're allowing people to interact in the inert space, which logically makes no sense. The possible consequence of coding around this? If someone does not realize a modal has appeared, they can accidentally dismiss it by clicking without even knowing there was a dialog.
I'm actually quite happy the dialog element doesn't have that close-by-clicking-outside functionality by default. I believe it could just confuse less experienced users who often tend to click here and there quite randomly when they try to find out how the page works.
I think it's such a common feature it should have been an optional attribute, similar to the 'method="dialog"' attribute. Also, the only time I've found it frustrating is when it closes "on mouse up" (i.e. you select all text by dragging the mouse over it and accidentaly reach outside the modal).
Been using jQuery dialogs for years. Coming from a desktop development environment they make a lot of sense (tried all sorts of other options) They are very easy to implement and customize and they work great on mobile devices.
Indeed, a jQuery.UI dialog is zillion times better then bootstrap ones. The only down side is by default the jQuery.UI dialog looks like something from the 1990's. The bootstrap dialogs (modals) look great, but they are "really" poor to deal with , where as jquery.UI dialogs are fantastic to work with, but out of the box need some love and care style wise. Been saying for years, sooner or later, browsers will finally get a good dialog and modal dialog option. Since a confirm() or alert() causes blocking code (not asynchronous)? Then alert/confirm are the only 2 functions left in a browser that can halt/block code. I'm betting they will at least try to depreciate these 2 features as a result. I'll stick with jQuery.UI dialogs at least for this year. And I have some "user" controls and library code based in jQuery.UI dialogs that just work for me. However, the new dialog feature? About time!!! And this dialog feature looks to be "flowing" though all mainstream browsers. (Edge, Chrome, Firefox, and the mobile browsers). So, the adoption rates looks like it should be "reasonable" safe to start using this feature this year (2023). The amount of hand stands people have endured to pop some simple dialog in a browser over the years? Ouch!!!
@@Albertkallal You can override the classes in the jQuery UI (classes attribute) but I'm not sure how modern it can be made ;) I not good enough with CSS to do it ;)
In fact the dialog implementation in html is not fully modal as it does’nt interrupt and wait in the JavaScript function that call the showmodal this results in a modal in context of html but not modal in regard of JavaScript… you cannot replicate behaviour of confirm() nor prompt() even alert(). This may be quite annoying if you just want a confirmation of overwrite only for existing data in a generic save data function. Or may I have miss something?
This dialog element is amazing not just for accessibility but it comes with its own show/close API that can be easily implemented in React with a useRef hook. This should be the direction for web/mobile app development - making life easier for both the end user and developer.
It's long overdue. There have been far too many hacky ways of doing things in the frontend, these things should just exist by default.
I wish the details element could receive a bit more love.
Came to ask this question. thank you!!
any way you could post small code sample of react/useRef for this?
@@scottbrown-xveganxedgex2799 there's plenty online, just reference the dialog and close it with the ref.current.showModal() or close()
Nty, I like my hard life 😆
There's multiple ways one could explain an HTML tag but Kyle's way is the absolute best. Always so grateful. Thanks much))
There are*
@@encycl07pedia- the error was unintentional ( not deliberate). ))
One of the big advantages of a platform such as this is that many teaching styles are available, and you can find those which suit your learning style the best.
That's one thing that neither college nor work will necessarily make so readily accessible.
Wow, I remember implementing modals like that 11-12 years ago for my pet projects back in the times when I studied at school. So surprised that only now it became a standard feature
Bureaucracy
@@josiah7913 could it be so that it's from 2013, but back then it lacked a couple necessary features, and hasn't been supported until recently?
@@josiah7913 I see, then it makes sense that nobody bothered using it
I think grid took like 2 decades to be implemented lol xD
I just spent a good chunk of time creating a model for a project . Nice to see the simplicity of this new html element. Thank you!
Was just about to create one and this popped up… 😮
@@christianwatson6500 same
The best feature imho are stacked modals. If you try to create a modal inside a modal the old fashioned way with the outer modal(overflow:hidden), it will display the stacked (inner) modal only inside the already opened modal. With you're completely free to stack and overflow as you like.
What's the use case of a stacked modal?
@@encycl07pedia- Maybe confirmation dialog? Asking before submitting changes or showing error message...
@@encycl07pedia- it is excellent way to provide a sub-par interface. And the “easiest” way is to provide a confirmation to some action inside a modal. Users will then know that you study (low) quality UI.
Just a small tip. At least on VSCode, do you know that you can change the element's tag name more easily ? Click on the tag name then press F2. It avoids having to modify the name on the closing or opening tag because it works both ways.
Thanks
on which system? doesn't work for me
@@shufflepack MS Windows, F2 is the default key to rename things on Windows (files, folders, etc.)
Thanks
Ctrl+d / CMD+d as well
8:41 I've been familiar with modals for over a year, but it wasn't until I watched your video that I discovered the save form inputs feature doesn't require JS. That's a fantastic revelation!
7:50 I have a small tip for those who declare global CSS variables using :root{}. Keep in mind that you cannot apply them to the backdrop because they are considered 'undefined' within the same module level as the :root{} and they're considered out of scope
I am doing that over a year
The top for 7:50 is good info. How would you fix this?
I always watch Kyle's videos before I sleep... This time I dozed off with my hand on the phone's keyboard.
Sorry for the emoji spam lol
Spent 10 minutes deleting emojis here
@@RogerHNobrega wtf
@@IStMl Sorry bro! read the above comment lol
literally life saving, i've never made a modal before and was a bit scared lmao, this is so easy and simple THANK YOU!! :)
Awesome! Dialogs and modals has always been a pain point in front-end dev.
They always seemed relatively straightforward to me when using a css/js framework like Bootstrap, but at least now it should be even simpler since it's becoming a base feature of HTML5.
@@TheDragShotthe fact that you rely on a framework to do it proves the OPs point
Of course, they're even more of a pain to the user. I can't remember when I last saw a web page modal that wasn't there purely to obstruct normal use.
Pretty neat. I like that it's allowing to close with the escape key by default.
It would be a bit cleaner to wrap the contents of the dialog rather than using coordinates on click though.
Then it's just : `dialog.addEventListener('click', e => e.target !== wrapper && dialog.close())`
this also solves a non-rectangular or rounded corners dialog issues.
Well, maybe it is better to check whether the backdrop clicked or not rather wrapping it?
@@The14Some1 yes it would be better.. but you can't check clicks on pseudo elements.
Your code would close the dialog when user clicks on another element inside the wrapper. The condition should rather use the contains method: `wrapper.contains(e.target)`
@@Grouiiiiik or you can do this:
wrapper.addEventListener( "click", (e) => e.stopPropagation() );
dialog.addEventListener( "click", () => dialog.close() );
Thanks for highlighting things that can be done with native/raw HTML.
Rather than introduce complexity with getBoundingClientRect (which may potentially trigger all kinds of false positives from dropdown menus, rounded corners, and other dialog interaction that may overflow the cursor rectangle target), why not simply wrap the content inside the dialog with a div and set an event listener that closes the dialog when that content wrapper div loses focus? In fact, I wonder if the dialog object itself might not also raise a blur event somewhere that we can detect and handle. Awesome video, in any case, Kyle.
Yeah, even without the div, seems like it should be possible to get the actual target in the bubbling phase and compare selector to check if it is the backdrop element or not.
@@dsego84 As a result of this discussion, I've been toying around with this in CodePen and have not been able to trap the actual target natively. The main problem is that the full page backdrop is part of the modal. In effect, when the modal is open, all clicks all over the page are regarded by the DOM to still be inside the modal. In practice, there is no way for the modal to lose focus at runtime while open. The div trick works. It's a decent workaround (a better workaround than getBoundingClientRect in my opinion) but it's not perfect. The div style must be forced edge to edge to occupy the entire dialog. If you don't do that, a click on any whitespace inside the dialog but outside the div counts as a blur event and the dialog closes. I now share Kyle's frustration, all of these tricks should be future polyfill. Truth is, the dialog object itself should natively raise an event when the backdrop is clicked. Even easier, I'd love a property we could simply set to change the modal behavior to make it close on such a click. Frankly, if we are making a wish list, I'd like both. In fact, I'd also like the backdrop to be a property of the dialog object instead of a pseudo style. My current assessment is the dialog tag is a big improvement on the usual hassles with modals but the implementation is only about 90% there. I'm still experimenting to find a universal elegant solution for modal close-on- blur. My gut still tells me that something else somewhere must bubble to the DOM that we can use as a trigger.
@@robertholtz Wow, thanks for poking around. Agreed the div trick is a decent workaround. Too bad it's not possible to trap the target natively. Thanks for the write-up as well!
It`s good idea but you have to be careful and be aware that dialog element has many default styling properties (e.g. default 1em padding)
@@krzysztofrozbicki1776 You are quite right. I pointed that out later in the thread when I started actually testing this out. You must override dialog's default styling and make sure your control div spans edge-to-edge of the entire dialog. Any click on the whitespace inside the dialog but outside the div counts as a trigger and the dialog closes. I'm still looking for a more elegant solution but I believe this is still better than getBoundingClientRect. With the div approach, not overriding the default dialog padding is the only way I have found that may raise a false positive but that has an easy fix. In contrast, getBoundingClientRect has many potential false positive scenarios, some of which are so involved to guard against that it nets out to be far less work to just do modals the traditional way. I prefer modals that close on blur and I want to take advantage of dialog's baked-in behavior. The div trick enables developers like me to achieve both. My quest continues for a still-better detection method.
Other way to handle click outside is to listen on click for dialog element and, add `e.stopPropogation` for dialog body. This can also handle the edge case when border is rounded.
Thanks for bringing this to people's attention👏. I am currently "migrating" from A11yDialog (which is great btw) to native, now that implementations got so much better over the last couple of years. Also saves so much custom and library code all over: HTML, CSS, JS; from several kb to a few dozen lines all across.
Thanks for bringing up a11y-dialog. So you'd recommend just using this method over a11y-dialog? Is this method as accessible as a11y-dialog?
Man you realy save me, i was using the dialog modal but in react and doing preventDefault() doesn't work very well, but now i understand why, thanks a lot!!
Mind blown. Best tutorial ever! Thank you!
Great content and presentation/demo. Thanks!
ngl the timing of me finding this out is perfect because i was just working on a modal for a project iam doing
I like the way you explain things. I came from express video and the way you explain things and giving people some really nice tips or feature that I don't even know exist. Keep doing it man!
Holy, I was just searching this 3 days ago. Now you just make my day bro, thanks!
Finally, something! I still don't understand why for so many years HTML doesn't have such simple features like population of or / with an array. Or even to populate a table you need to create elements or deal with strings and innerHTML
dynamic DOM changes is exactly why JS exists.
You're talking about logic there. HTML is simply a container, it has no concept of logic.
For logic we use JS, or, to build on that you could use something like JSX.
But you *are* populating with an array... of elements. Markup is markup, the only way to represent data structures or anything else in it is with elements.
I Thank you sooo much for really making the Web development simple. Your videos are truly interesting to watch and learn
Great video! I was already aware of but you explained some features that make it worth using (especially the keyboard accessibility with modal dialogs). Previously I didn't see any point using this instead of JS implementation I already had implemented.
Native HTML/CSS is always preferred to a Javascript implementation, in my opinion.
Though I'm a particularly biased developer that has NoScript always on by default.
been using this one for a looong time now. Amazing
I'm kinda new around here so I didn't know about your blog - excited to see the amazing content you have on there!
Thanks!
You are very welcome!
Ma sha Allah! That's really aewsome. Thank you Kyle for sharing the update!
Man, thank you very much for what you do. You really help people.
This is going to save an old pet project that I abandoned a while back. Thanks!
Neat! I had no idea about any of this! Definitely going to make use of these in future
bruh, it was introduced in chromium 37 (2014). we just weren't focusing on it all this time ;)
I'm not gonna lie. I had to look into this and it's been supported for quite a while. How has this not been the top response for anytime someone is asking on how to make modals/dialogues?
Because everyone is obsessed with creating custom elements instead of using web standards.
HTML covers so much, yet we keep reinventing the wheel.
@@Daijyobanai I can see that. It’s a shame because the same thing can be accomplished in less code. I honestly dont get it :/
It is incredible how informative and efficient these videos are. Thank you so much!
Great video, short and to the point. You have a new sub!
Thanks for this and the YT algorithm for showing it to me at the right time (even if it creeps me out that it knows...) . This would be perfect for HTML/JS games to display dialog and menu screens.
I hope they will do the same with a search element. HTML5 is doing great
This is game-changing! I wish stuff like this made it into HTML/CSS/JS more often
You should go read the HTML docs. A lot of native elements have been introduced over the years. Dialog elements have been around for a few years already, just not widely known
You are my hero. Your videos are always amazing, straight to the point, and useful!!
I am not 100% sure why this is in my suggestion feed, but I am not complaining. Being a hobbyist coder and no one ever hiring me, making me use HTML on a daily basis, a lot of this is stuck in reference books and code example snippets. I wish I could keep this in my head more.
I am amazed at how HTML has changed since the days in high school when I would make pages for my old GeoCities site. Things have sure changed.
Awesome can't wait to try it on future projects
When I clicked, I was hoping this was a video showing how the world had reinstated the synchronous modal which was removed after IE 5.5, the showModalDialog(url) method... it was synchronous just like confirm(message). Confirm() can only show a text-message and return OK/Cancel, but showModalDialog() could show and return whatever you wanted. And you could have your code in one place without needing to scatter it among callback methods and global variables... But, as always - great video!
Holy freaking crap! Where has this been all my life
Looks nice and simple to use. Can you also animate the modal when is shows and close?
Seems not. Tried to apply (.modal[open]) opacity or simply background color transition, but it didn't work. Even if it would work with appearing, it won't with disappearing anyway.
To use benefits of dialog element and animate you will have to add and remove to dialog class with animation styles.
of course not!
The dialog element adds some CSS by default, if you want to use flexbox and add display: flex to your .modal css class your modal will be visible on the page before clicking on the button.
The only solution I've found is toggle a class who add display: flex when clicking on open and close buttons....
Idk if a cleaner solution exist...
That's awesome. And if you can guarantee that all of your visitors have browsers released March 2022 or later (that's when Firefox introduced support), you can actually use this. Otherwise, you'll be implementing that dialog twice.
The dialog implementation is indeed awesome, but for general use you'll have to wait until at least 2025. We still get issues reported relating to features that became available in 2020 - a customer using an outdated iOS version as a test device is not uncommon and I know from my private surroundings that a horrifying amount of people somehow use outdated software even when updates are available. At least we don't have to struggle with Internet Explorer anymore. :)
Thank you, my projects are now tab safe.
Kyle, you are THE MAN (intended as a compliment).
Wow .. massive demonstration of enthusiasm and structured presentation for information sake - thanks for sharing!
I will definitely be using this element in my latest project.
Kyle, you nailed it again man. Well done. Very useful content. 👏🏻👏🏻👏🏻
Jesus... I'm been missing your videos. Just noticed that I wasn't subscribed to "all". Fix now 🤗Keep up the great work you are doing Kyle!!!
Love that Jackson bro! I have a black Jackson Kelly Pro with the flame headstock. Great video too, thanks!
Just needing to do one of these thanks, perfect timing
I've seen your blog website and it's awesome. But I hope you would add some basic features to it, like a "Back to Top" button on the individual blog page, a sidebar containing the table of contents on the individual blog page so that the user would be able to jump to the content they want to read, a comment section below the blogs, etc.
Pretty amazing to see this new feature being implemented. Maybe we won't be so dependent on Bootstrap modals anymore.
Pretty amazing GUI development indeed, we now have one of the ONE-LINER basic elements introduced WAAAY back in 16-bit Windows some 30 years ago. Today, we can all rejoice that even the amateurs running online banking, e-commerce or government portals are able to reliably and portably (within a VERY narrow definiton of portability. even my fridge is portable, kind of) create dialogs that may some day bring their customers a more grown-up experience if they can resist perverting the experience, LIKE YOU, DEAR SIR, JUST DID in the end of an otherwise informative video.
What? "I want to exit a modal dialogue by clicking outside of it"? Because others do that? Because of never having used any real software except a web browser? Monkey see monkey do? How anticlimactic. This is why we can't have NICE THINGS, even when the holy V̶a̶t̶i̶c̶a̶n̶W3C sends us new gospel, people can't help but turn it into crap and spray it around at NVMe speeds. With the best of intentions, of course. Boy...
Question: when the end user closes a dialog by clicking outside of it's borders, WHAT IS THE EXPECTED ACTION? Ok, Agree, Cancel, Save and exit? Yes? No? Quit, burn house and kill all the newborn? There is A REASON why there is no such functionality. It is BECAUSE. Think about that, please. Can ideas of aesthetics, usability, webdev BDE and (last but def not least) keeping users out of asylums coexist? Can I ever talk about calm computing without being as far as calmness as possible? Yes we can (hope I can, too)
Can't get WIN16 API and MessageBox(NULL,"To be or not to be?","I am a dialog title",MB_QUESTION|MB_YESNO|MB_APPLMODAL); back, thank god, but I have to say that it is getting tired to watch people foaming at the mouth year after year when collective stupiditiy has again invented some ancient wheel again, less efficiently this time,because YES, WE CAN (make everybody and their cat eat our DOG food. and the only version that is good enough is the next version, and energy and Moore's law is a universal constant proven by scientist, right?).
So, showing the dialog requires now a more complex, diverse and delicate system software compared to Windows 3, but also a BROWSER (not much of a choice since there's just rebranded Chromiums and Firefoxen left because developers have to still develop the development like there's nothing better to work on than breaking other people's stuff without warning. When are they going to freeze the features and move on to to coding something useful instead of bloating and regressing their bugridden compulsory software monsters, that are A MISSION CRITICAL PLATFORM for many and have upgrade nagging, have sandboxes and crashpads farting inside my process table wasting my precious memory and still not preventing crashes, just showing useless iconography. And is "ERR_NAME_NOT_RESOLVED" really the best way a big company like Google can explain a dns failure to their users?) too and takes at least a gigabyte of scaffolding around it (I DO NOT OWN A TURING MACHINE AS IT IS SUPPOSED TO HAVE INFINITE SYMBOLS. I have finite RAM on my system) to render even the ugliest non-movable non-END-USER-stylable slab of pixels with a button -- not looking like a button -- THAT'S GREAT! since it "works even better than what modals had before" (a modal failing in modality is... well. ununderstandably bad. no excuse for nerds there. I want to puke.)". Clearly, Sir, you are wrong. Maybe that is the cost of having the blessing of not ever writing actual desktop programs for a native development environment.
Let's do the time warp again!
@@janimakinen1455 modals are the single most unnecessary / easily abused / aggravating UI element in the set of all UI elements.
If you are using a modal then your UX skills are woefully inadequate and you are abusing the user.
@@aarondcmedia9585 Modals have their use, for example in the case of a CRUD web app, to prevent users from accidentally losing their progress, showing a modal when the app is in a dirty state and about to be closed is a good thing to have.
@@DesignThinkerer I disagree completely.
Autosave the data as it changes. When they close the form it doesn't matter, you already saved it. When they return to the form, you can repopulate it automatically, or let them choose to repopulate from their last visit.
This is like UX 101. Interrupting a user who is doing something is about as bad as UX gets. I would prefer to not treat my users like idiots who don't know what they are doing, and if they are completely new, I would prefer to make it a frictionless experience.
@@aarondcmedia9585 I agree with you, at least to a point. I hate modals personally. I'm also much more of a fan of server-side action instead of putting the entire weight of the site on the user's end.
I figured out dialog element a few months ago and I got very astonished! This is a very good tool to make modals.
I only got sad with the fact of that it is not possible natively to close the modal by clicking outside it (clicking in the ::background space), and although they recommend the getBoundingClienteRect() function, it doesn't work correctly when your modal has border-radius and you click on that specifcly space. But I think it's going to get better in the future.
Dude, best channel ever! Kudos!!
always clear, concise and knowledgeable
Aw, this makes me want to build a website again... They're making it easier bit by bit. Less hacking needed to do what our clients have thought were normal features all along.
First time viewer. Great stuff. This channel is an easy subscribe.
OMG!!! This is soooo convenient!
Thanks for sharing!
@10:10 Click on backgrop to close modal only happens on the web. No OS I know of does this. We have added unnecessary complexity and trained the users to expect an anti-pattern to work.
So finally, modals behave like they should. And yet, I bet every web dev is going to have to add the JS for click outside modal to close because the boss/customer want's to have it like this. Why is there no tag attribute or at least a JS property like open or returnValue to configure this? Why W3C? WHY?
I only wish I knew about this sooner. I spent a fair amount of time creating dialog boxes for my current project using Firefox for testing. I solved all the problems of backdrop, tab navigation, etc. BUT unfortunately when I run my code on Chrome I get annoying flashes that are completely unacceptable and will have to be fixed. I've known about this problem for months and was thinking that maybe the dialog element would be the solution, but hadn't yet found time to investigate. So now you've convinced me the dialog element is the way to go.
Using firefox was your first mistake!lol!
Amazing information once again, Kyle! Thank you. 👍
There's one single thing that I wish was covered, but perhaps it was left out due to the complexity involved. I'm developing in React and most of our applications require way more complexity of handling modals than a single one per page or application. How would this work with multiple modals being triggered from the same location? Not overlapping, obviously, but perhaps I have an extremely custom layout with multiple flows that can be triggered from the same location. I do believe you'd eventually dig into unique identifiers, but I'm just wondering if it has support for that at all.
Nonetheless, gold information right here. We can finally start dropping libraries handling stuff like this. Will dive into how this could be implemented in React with Redux perhaps or with programatically triggering these modals. Much appreciated!
did you find anything yet? I've been looking as well.
👌👍🥳 awesome element! great news, everyone!
Great video. Thank you. I suggest for next video a practice about a carousel of images and modal window show us the image. When user click on the image , image pop up and and the other images fade.
Nice HTML you got inside this tags.
Finally! A true Game Changer! Subscribed!
Nice work! If you wrap up your dialog with a promise 'return new Promise(resolve => {
// dialog
const dialog = document.createElement("dialog")' then you need to capture the cancel event ' dialog.addEventListener("cancel", e => {
resolve("cancel")
})' and finally add a call to resolve to your click event handler '...dialog.close()
resolve("cancel")..."
The problem with the closing dialog approach is that if you add a HTML range input selector it'll automatically close the dialog/modal even if the selection is within it.
Kyle, amazing and super useful video! Thank you 🍻🍻
You never cease to amaze Kyle.
great and easy explanation of everything here, what a nice feature!
great post, wasn't aware of this. also, I'm concerned about your second guitar leaning on the stand.. too many headstocks have broken that way (once to me!) so please be careful! haha
But the scrolling is kind of a problem. How do you get rid of that? I don't want the page to scroll when the modal is opened up.
I'm not sure if it's still best practice, but I like to use a link styled as a button to cancel/close, and an actual button for save/submit so the cancel button can't be the default behavior if you hit enter inside an input in the form.
I also apply a click handler to the body to close the modal, then a stop propagation click handler on the modal.
That is a real nice introduction to the dialog element! I was aware of it, but did not dive into details until now.
Since I was a little set back by the whole "getBoundingClientRect"-thing, I prodded a little bit around. Although you can not distinguish between Dialog and Backdrop on click, you can, however, get rid of the "getBoundingClientRect".
The PointerEvent has "offsetX/Y" properties which are negative when the click is left of or above the dialog. Further "offsetX > modal.offsetWidth" holds for clicks right of the dialog and conversely "offsetY > modal.offsetHeight" for clicks below the dialog.
I do not know, however, if this still holds for very big dialogs - still could, I guess.
There is a bug in your clicking outside detection. If you have an element that overflows the modal, let's say a dropdown menu, and click on an option outside of the modal bounds, it will close the modal.
@@Chalisque You can probably check the click event target and make sure it's anything but the modal but I haven't tried
@@TehHayzen That's true. You could probably just check if the backdrop is what's being clicked and that's it
worth noting: doing animations with dialogs is sometimes hard!
Is it because it disappears instantaneously instead of fading out for instance?
@@supernovaw39 it can be done with the dialog element, right?
@@ManuelSanchez-ih5qx The way I last did it is I used JavaScript to initiate the animation and run dialog.close in ontransitionend
@@supernovaw39 yes, i posted comment with link to gist of code I use but I guess it's shadow banned by youtube...
Gorgeous explanation. Thanks.
The dialog element is great, but unusable really for Route based modal experiences using SSR frameworks - just the one downside to look out for. Great video!
The cancel button was still of type="submit" so it did exactly that: submitting the form. A type="button" doesn't. Web Standards 😉
There are several native button types in HTML with useful default behaviours since ever. It's worthwhile learning HTML fundamentals to save yourselves the energy recreating what's already in the browser. Many devs and designers believe they are doing a better/smarter job reinventing wheels, when all they do is creating another flat.
Just because the native HTML select dropdown (still) sucks, doesn't mean the other controls and elements a shit, too. Learn to use them and what they're for. Save yourselves a lot of coding and your users a big dump of pointless code they have to download for an often worse experience.
I wonder how much HTML this guy actually knows, lol 😅 I've had brain farts where I'm just "... oh" and change from input to button or something but jeez
@@computer_toucher theres only 135-ish elements in HTML5 😁 no big deal :)
Yes but it submits the form using the dialog method, which means it closes the dialog. Exactly what we need. According to mdn the dialog method does not submit any data, it only saves the data and closes the dialog.
Been there, done that. So far I've re-invented dialog boxes and web components. A waste of time but think of all that exercise my brain got!
Great post! Regarding your final comments... The reason it doesn't allow you to click outside to dismiss the modal is because all that area is supposed to be inert. By working around that, you're allowing people to interact in the inert space, which logically makes no sense. The possible consequence of coding around this? If someone does not realize a modal has appeared, they can accidentally dismiss it by clicking without even knowing there was a dialog.
This is really great man!
Really Helpful, thank you mane!
As usual, super fuseful!! Thanks!
I'm actually quite happy the dialog element doesn't have that close-by-clicking-outside functionality by default. I believe it could just confuse less experienced users who often tend to click here and there quite randomly when they try to find out how the page works.
I think it's such a common feature it should have been an optional attribute, similar to the 'method="dialog"' attribute. Also, the only time I've found it frustrating is when it closes "on mouse up" (i.e. you select all text by dragging the mouse over it and accidentaly reach outside the modal).
Awesome video, thanks Kyle!
Been using jQuery dialogs for years. Coming from a desktop development environment they make a lot of sense (tried all sorts of other options) They are very easy to implement and customize and they work great on mobile devices.
Indeed, a jQuery.UI dialog is zillion times better then bootstrap ones. The only down side is by default the jQuery.UI dialog looks like something from the 1990's. The bootstrap dialogs (modals) look great, but they are "really" poor to deal with , where as jquery.UI dialogs are fantastic to work with, but out of the box need some love and care style wise.
Been saying for years, sooner or later, browsers will finally get a good dialog and modal dialog option.
Since a confirm() or alert() causes blocking code (not asynchronous)?
Then alert/confirm are the only 2 functions left in a browser that can halt/block code.
I'm betting they will at least try to depreciate these 2 features as a result.
I'll stick with jQuery.UI dialogs at least for this year. And I have some "user" controls and library code based in jQuery.UI dialogs that just work for me.
However, the new dialog feature? About time!!!
And this dialog feature looks to be "flowing" though all mainstream browsers. (Edge, Chrome, Firefox, and the mobile browsers).
So, the adoption rates looks like it should be "reasonable" safe to start using this feature this year (2023).
The amount of hand stands people have endured to pop some simple dialog in a browser over the years? Ouch!!!
@@Albertkallal You can override the classes in the jQuery UI (classes attribute) but I'm not sure how modern it can be made ;) I not good enough with CSS to do it ;)
@@Albertkallal Can't wait to get something, anything, better than alert/confirm! At least something you can slap some CSS on!
@@Albertkallal Agreed!
Thank you! You remind me of the guy from Let's Get Rusty, Bogdan I think. Great presentation; thanks again!
It seems this tag does not prevent parent scrolling if the parent container is long.
Is it me or is the normal behavior ?
This is amazing!
You are an angel sent for new Progammers :)
Good. Hopefully now we'll have modals that can be closed with the escape key
Wow, that's amazing! Thank you! 🔥
In fact the dialog implementation in html is not fully modal as it does’nt interrupt and wait in the JavaScript function that call the showmodal this results in a modal in context of html but not modal in regard of JavaScript… you cannot replicate behaviour of confirm() nor prompt() even alert(). This may be quite annoying if you just want a confirmation of overwrite only for existing data in a generic save data function. Or may I have miss something?
Wow, great video, nice feature, I have so many ideas to implement it.
Nice job! And a new subscriptor for you
I ran into issues when using the following CSS code:
* {
margin: 0;
padding: 0;
}
The dialog does not work well with this CSS. Just be aware.
Great code demo dude, thanks