Vue.js hunt for perfect modal

Yauheni Prakopchyk
Jul 18, 2018 · 2 min read
Image for post
Image for post

Hey. Today we will pursue our dream of a perfect modal. Perfect means:

  • It floats above everything else.
  • Is not blocking.
  • Supports nesting of any depth.
  • Doesn’t collide with other elements on the page.

Seems easy enough, right? Let’s glance over different solutions I harbored.

Full screen overlay

Image for post
Image for post

For this solution we create invisible overlay over a whole window. Overlay catches all clicks.

Template

Style

Looks fine, doesn’t it? Except that it’s blocking… Which means that, in order to open another modal, a user has to close the current one. That’s 2 actions and we can do better.

Here’s the component code.

Stop propagation + document event

Image for post
Image for post

For this approach we attach a click event handler to document.body, we also prevent click event propagation on modal click.

Template

Script

The downside is that any other modal will prevent bubbling to document.

Meaning no nesting ¯\_(ツ)_/¯.

Here’s the component code.

Document event + event target check

Ok. This is an ultimate solution. For the most part it’s the same as a previous one. Only that we won’t prevent propagation. And instead we’ll check the event.target.

Template

Template is regular. Nothing special here.

Script

We check, if a click landed on a child. In case it didn’t — modal hides itself.

Here’s the component code.

Let’s test our modal.

  • ✔ It floats above everything else.
  • ✔ Is not blocking.
  • ✔ Supports nesting of any depth.
  • ✔ Doesn’t conflict with other elements on the page.

Done.

Check the source code if you’re looking for complete components.

Tell me if anything is wrong or this modal is not nearly perfect in your opinion. : 3

Connect Deeper

If you like what you just read, please subscribe to our newsletter to get more content from Epicmax and bonus code that will give you a discount for first 30 days working with us.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store