Tool Shortcuts in JS

One major feature for drawing apps is the ability to use shortcuts to switch between tools. I’m going to show how I implement them and add a tooltip to tell the user what the shortcut is.

document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keyup', handleKeyUp);

In order to tie a function to a specific key, the easiest way to “look up” the correct keycode you want is to simply use console.log:

function handleKeyDown(e) {
console.log(e.code)
}

Once you know the correct code, add a conditional for the keys you want:

function handleKeyDown(e) {
if (e.code === 'Space') {
state.tool = tools["grab"];
onScreenCVS.style.cursor = "move";
} else if (e.code === 'KeyB') {
//reset old button
toolBtn.style.background = "rgb(131, 131, 131)";
//set new button
toolBtn = document.querySelector("#pencil");
toolBtn.style.background = "rgb(238, 206, 102)";
state.tool = tools["pencil"];
onScreenCVS.style.cursor = "crosshair";
}
}

I’m making the space bar activate the grab tool only while held, so I have a keyup event as well.

function handleKeyUp(e) {
if (e.code === 'Space') {
state.tool = tools[toolBtn.id];
if (toolBtn.id === "grab") {
onScreenCVS.style.cursor = "move";
} else if (toolBtn.id === "replace" || toolBtn.id === "pencil" || toolBtn.id === "curve") {
onScreenCVS.style.cursor = "crosshair";
} else {
onScreenCVS.style.cursor = "none";
}
}
}

Since I never changed the highlighted button, I can use that to return to the previous tool once the space bar is let go.

A shortcut is kind of useless without a way to tell the user about it, so we should add a tooltip.

HTML:

<div class="tool btn" id="pencil">
<span class="tooltip">Shortcut: B</span>
<h3>Pencil</h3>
</div>

CSS:

.tooltip {
visibility: hidden;
pointer-events: none;
position: absolute;
z-index: 1;
color: black;
background: rgb(255, 255, 199);
text-align: center;
width: 100px;
font-family: "04Font";
font-size: 16px;
/* border-radius: 6px; */
padding: 5px 0;
align-self: center;
transform: translateX(-160px) translateY(60px);
transition: 0.3s all;
opacity: 0;
box-shadow:
2px 0px rgb(255, 255, 199),
-2px 0px rgb(255, 255, 199),
0px -2px rgb(255, 255, 199),
0px 2px rgb(255, 255, 199);
}
.tooltip:after {
content: "";
display: inline-block;
width: 2px;
height: 2px;
position: absolute;
top: -2px;
right: -2px;
background: rgb(255, 255, 199);
box-shadow:
-2px -2px rgb(255, 255, 199),
0px -2px rgb(255, 255, 199),
0px -4px rgb(255, 255, 199);
}
.btn:hover .tooltip {
visibility: visible;
opacity: 1;
}

Much of this is just styling, but the important one to note is this: pointer-events: none;. Without this line, the tooltips can get in the way since they won’t disappear if your mouse hovers over the tooltip itself. With this line, you can smoothly move over other buttons without the tooltip getting in the way.