Block Editor: Select on Enter in the Block Inserter – So Good!

Block editor select on enter so good image

This should be baked into the Gutenberg Block Editor by default. I almost get annoyed anytime I’m working on a site without it. Save yourself some clicks, honey!

What it does…

In the Block Editor’s Block Inserter popup, when you’re typing to find a block and insert it, just hit enter and this script will auto select the first block. Hit enter again and the block will be inserted. So frickin handy.

Why it does it…

There’s just no reason to have to reach for the mouse after you’ve typed and found the block you want. Seriously, why is this not in the Block Editor already?

How it does it…

This uses javascript to check if you are typing inside the Block Search, and if so it enables the Enter key to move focus and trigger inserting blocks.

Download JSON for importing into Code Snippets Pro
Download PHP for adding as a plugin or copying into functions.php

See the code…

<?php

// Block Editor: Select on Enter in the Block Inserter
// https://snipsnip.pro/s/180
namespace FhkH6D;
function block_editor_select_on_enter(){
	if ( !function_exists( '\get_current_screen' ) ) { return false; }
	$screen = \get_current_screen();
	if ( method_exists( $screen, 'is_block_editor' ) && $screen->is_block_editor() ) {
?>
	<script>
	const FhkH6D_domReady = cb => {
		"interactive" === document.readyState || 
		"complete" === document.readyState ? 
		cb() : document.addEventListener("DOMContentLoaded", cb)
	};
	FhkH6D_domReady(() => {
		document.addEventListener("keypress", function(event) {
			if (event.target.classList.contains("components-search-control__input") && "Enter" === event.key) {
				let el = document.querySelector("div.block-editor-inserter__panel-content > div.block-editor-block-types-list > div > div.block-editor-block-types-list__list-item");
				el && el.firstElementChild.focus()
			}
		})
	});
	console.log('Block Editor: Select on Enter in the Block Inserter');
	</script>
<?php
	}
}
\add_action( 'admin_print_footer_scripts', '\FhkH6D\block_editor_select_on_enter' );