Detecting key presses in a custom code block

I’ve written an audio plugin for obsidian, renders an audio waveform in a custom code block, stop start buttons and region select for looping over sections. Now I’d like to add some keyboard control; space bar for play/pause, keys for setting loop markers, other keys for slow down/speed up. My best solution so far is custom keys but I’d rather be able to use single keystrokes without modifiers. So my question is, is there a way to detect specific keypresses in a custom code block, without those keys appearing in the containing note…

OK, so I have this so far. I had hoped that event.stopPropagation(); in the keypress handler would prevent the keypress putting a charactier into the note but it doesn’t.

Thoughts appreciated. thanks.

			el.addEventListener("mouseover", () => {
				console.log( "in"  )
				document.addEventListener("keydown", handleKeyPress);
			});
			
			el.addEventListener("mouseout", () => {
				console.log( "out" )
				document.removeEventListener("keydown", handleKeyPress);
			});
	
			function handleKeyPress(event) {
				const keyPressed = event.key; // Get the specific key pressed
				event.stopPropagation();
				console.log(`Key "${keyPressed}" pressed while hovering over the element`);
			}

I’d forgotten to add event.preventDefault();. All working well now.

            el.addEventListener("mouseover", () => {
				console.log( "in"  )
				document.addEventListener("keydown", handleKeyPress);
			});
			
			el.addEventListener("mouseout", () => {
				console.log( "out" )
				document.removeEventListener("keydown", handleKeyPress);
			});
	
			function handleKeyPress(event) {
				const keyPressed = event.key; // Get the specific key pressed
				event.stopPropagation();
                event.preventDefault();
				console.log(`Key "${keyPressed}" pressed while hovering over the element`);
			}
1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.