If one wrap both image and text with the input into a label, it appears to work without script.
<label for="input1">
<img src="http://placehold.it/350x50"><br>
Some text that should be visible
<input id="input1" type="text">
</label>
<br>
<br>
<br>
<label for="input2">
<img src="http://placehold.it/350x50"><br>
Some text that should be visible
<input id="input2" type="text">
</label>
<br>
<br>
<br>
<label for="input3">
<img src="http://placehold.it/350x50"><br>
Some text that should be visible
<input id="input3" type="text">
</label>
<br>
<br>
<br>
<label for="input4">
<img src="http://placehold.it/350x50"><br>
Some text that should be visible
<input id="input4" type="text">
</label>
<br>
I you can't use labels, I suggest you add an event handler, where you catch the "tab key", get the element with focus and either get its parent element (which likely contains your input and text and image) and scroll that parent into view
document.activeElement.parentNode.scrollIntoView();
or you need to calculate the document.activeElement
's position and scroll it to the center, and here is a excellent way made by ThinkingStiff which I updated with a scrollIntoViewCenter
method.
Element.prototype.documentOffsetTop = function () {
return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop() : 0 );
};
Element.prototype.scrollIntoViewCenter = function () {
window.scrollTo( 0, this.documentOffsetTop() - (window.innerHeight / 2 ) );
};
And here is a snippet showing the scrollIntoViewCenter
method.
Element.prototype.documentOffsetTop = function () {
return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop() : 0 );
};
Element.prototype.scrollIntoViewCenter = function () {
window.scrollTo( 0, this.documentOffsetTop() - (window.innerHeight / 2 ) );
};
window.addEventListener("keyup", myScript);
function myScript(e) {
if ('9' == e.keyCode) { // tab = 9
//find and vertically center focused input
document.activeElement.scrollIntoViewCenter();
}
}
<img src="http://placehold.it/350x50"><br>
Some text that should be visible
<input id="input1" type="text">
<br>
<br>
<br>
<img src="http://placehold.it/350x50"><br>
Some text that should be visible
<input id="input2" type="text">
<br>
<br>
<br>
<img src="http://placehold.it/350x50"><br>
Some text that should be visible
<input id="input3" type="text">
<br>
<br>
<br>
<img src="http://placehold.it/350x50"><br>
Some text that should be visible
<input id="input4" type="text">
<br>
<br>
<br>
<img src="http://placehold.it/350x50"><br>
Some text that should be visible
<input id="input5" type="text">
<br>
<br>
<br>
<img src="http://placehold.it/350x50"><br>
Some text that should be visible
<input id="input6" type="text">
<br>
<br>
<br>