Autofocus select2 Inputs When Clicked

Autofocus select2 inputs when clicked image

C’mon… make it easy on yourself. Especially if you’re using MetaBox.io ❤️ 

See that? With this snippet you get that blinky cursor so you can start typing right away without having to click again in the input. MAGIC!

What it does…

Forces a select2 input field to autofocus when clicked.

Why it does it…

On some sites I use a lot of select2 autocomplete dropdown lists (especially if I’m using MetaBox.io ❤️). But sometimes you click on or tab to those little buggers and the text input doesn’t focus. This tries to fix that.

How it does it…

This JS finds the select2 input and listens for clicks. When the dropdown opens, it triggers the input to focus.

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

See the code…

<?php

// Appends JS to the footer of admin pages. Forces select2 inputs to autofocus when clicked.
// https://snipsnip.pro/s/158

namespace ff2G6Nm;

if (\is_admin() && \current_user_can('manage_options')) {
	
	\add_action( 'admin_footer', '\ff2G6Nm\add_script_to_page' );

	function add_script_to_page() { 
?>

<script type="text/javascript">
	window.addEventListener('DOMContentLoaded', ()=>{
		if (window.jQuery) {
			jQuery(document).on('select2:open', () => {
				setTimeout(focusInputOfTheOpenSelect2,100);
			});
			function focusInputOfTheOpenSelect2(){
				const basicClass = '.select2-container';
				const opendClass = '.select2-container--open';
				const focusClass = '.select2-container--focus';
				const dropdClass = '.select2-search.select2-search--dropdown';
				const fieldClass = `${dropdClass} input.select2-search__field[type="search"]`;
				const field = document.querySelector(`${opendClass} ${fieldClass}`);
				if (field) {
					// console.log(field);
					field.focus();
				}
			}
		}
	});
</script>

<?php }
	
}