Skip to content

Instantly share code, notes, and snippets.

@feeela
Last active December 28, 2015 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feeela/7451908 to your computer and use it in GitHub Desktop.
Save feeela/7451908 to your computer and use it in GitHub Desktop.
Set focus to an input when hovering the assigned label using plain JS. If you need IE8 support, you'll have to include a polyfill for `forEach`.
<form>
<label for="test1" data-hover-focus>Test 1</label>
<input type="search" id="test1" /><br />
<label for="test2" data-hover-focus>Test 2</label>
<input type="search" id="test2" />
</form>
<script>
var hoverLabels = document.querySelectorAll( 'label[data-hover-focus]' );
for( var i = 0, len = hoverLabels.length; i < len; i++ ) {
if( hoverLabels[i].control ) { // make sure this is a label with an assigned input
['mouseover', 'touchstart'].forEach( function( eventName ) {
this.addEventListener( eventName, function() { this.control.focus(); }, false );
}, hoverLabels[i] );
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment