site icon

Hi, I’m Chris

I am a web developer teaching
regular people how to code

~ Welcome to my blog ~

Color input triggers mouse events when selecting color

The HTML input type of color can be a really useful way for users to pick a color of their choice.

When we click on the input, it will then open up a color picker to select from. The color picker popup will depend on the browser/platform you are using.

html color picker

This input we click on and the "popup" selector, for simplicity, are 2 separate things. When we move the mouse from the input area to the popup, the transition will trigger mouse events.

But why do we care about this?

Well, for most of my web dev career, I did not. However, I recently ran into an edge case where it caused a problem.

This codepen example will demonstrate:

https://codepen.io/chrisdixon161/pen/LYNGymy#code-area

The example is in Vue.js, but the result is universal. We click on the color input, and when we move to the popup, it disappears.

This is because of a case where I wanted the color input to be part of an options menu. And this menu only appeared when we hover over a section.

This resulted in the menu being active when we hovered over, and hidden when we moved the mouse away.

So, why does the color picker selector disappear?

As mentioned before when we move from the color input to the color selector, the selector is a separate section. Meaning we are leaving the main section, and going to the new color picker section, causing the mouse events to run.

This causes of main menu to quickly close and re-open, leaving us with the original state which is the color picker to be closed.

To see this in more detail, I have added a console.log to the codepen example.

This is obviously a very specific example, but something which may help you out if you are having the same issue.

But how do we resolve this?

Obviously changing the events which open the menu to click etc would help. Although I wanted to keep the mouse events in place.

Another way to solve this is to also run a function when we leave the color input, keeping the showOptions boolean as true:

<!-- Template: -->
<input type="color" @mouseleave="keepOpen" />
// script  
keepOpen() {
      this.showMenu = true
    }

And now our color picker is preserved when we hover over.

This is obviously a very unique case, but one which may help if you run into the same issue.


- By Chris Dixon

Chris Dixon is a web developer and teacher. Teaching thousands of students mainly in Vue.js React.js, WordPress and web development.