Fight the focus loss, inspect elements that like to disappear

Did you know it's pretty easy to inspect/debug elements that disappear when the focus is lost in Chromium-based browsers? What exactly do I mean by this?

Take this tiny UI I threw together for demonstration purposes. It has a button that, when clicked, will show a context menu beneath. To build it, I added a button and bound handlers to the click and blur events. When clicked, the context menu shows until the blur event fires.

Here it is in action:

Example of the button which shows a context menu when activated

All is well so far. But wait, why is the context menu not the same width as the button?

If I try to inspect the context menu, it'll immediately be removed, as the focus of the button is lost. This, of course, is great for the design, as I don't want the context menu to stay visible. However, I'll run into trouble if I want to inspect the elements that comprise the context menu to see what's happening under the hood.

There are a few tricks that developers have up their sleeves for this situation. The first is to make the context menu always visible so it can easily be debugged. This is a good option. However, it's only sometimes possible. The second one is to force the javascript source debugger to pause its execution, which stops the element from disappearing. However, pausing the debugger is a little hit-and-miss, and you lose the ability to inspect things, such as hover events.

But what if I told you Chromium-based browsers had a feature built-in just for this situation? Well, browsers such as Edge, Brave, and Chrome have a feature called 'Emulate a focused page'. You enable this under the 'Rendering' tab in the developer console

Developer console with the rendering options tab open

When enabled, a click on the developer console will cause the element to not lose focus

With 'Emulate a focused page' enabled, I can now inspect the context menu to investigate why the width does not match the button.

Inspecting the elements that used to disappear

Oh, silly me, I didn't set the width property.

All fixed :)

Example of the button which shows a context menu with the correct width when activated

Did you want to play with this yourself? Here's the stackblitz I put together for the demo.

⚠️
Note that it doesn't work in edit mode on stackblitz