I have a number of form fields spanning over the page fold. When pressing the "tab" key to step through each input/select field it sits the next field on the bottom of the page fold.
A few of my fields have tool tips, validation responses and auto suggest boxes that appear below the field. When tabbing to the field, you can't see these elements below the page fold.
Is there a javascript or jQuery script that can vertically centre the screen around a focussed input/textarea/select/button field instead of aligning to the bottom?
Setting the value to “-1” also allows you to programmatically enable tab focus. Say you have an element that you don't want focusable on page load but after some event, you'd like to be focusable—you'd use tabindex=“-1” and the “. focus()” function to add that behavior.
Headings, paragraphs, divs, and various other page elements cannot receive focus. Elements that are focusable are normally ones that users can interact with, such as links and form controls. There's generally no need to set focus on something if the user can't interact with it.
You can just bind to the focus event and then calculate the offset of the field and center it on the screen.
$(':input').focus(function(){
var center = $(window).height()/2;
var top = $(this).offset().top ;
if (top > center){
$(window).scrollTop(top-center);
}
});
Same from above with smooth scroll effect
$(':input').focus(function () {
var center = $(window).height() / 2;
var top = $(this).offset().top;
if (top > center) {
$('html, body').animate({ scrollTop: top - center }, 'fast');
}
});
Easiest thing would be to include the jQuery ScrollTo plugin and the jQuery Viewport plugin.
Then wrap every input + related other elements (validation response, ....) in a div.
On focus check if the div is completely visible, if not use scrollTo
. Done.
Of course this is a bit of a bloat but if you can live with the 2 more dependencies and an additional ~4kb this should work without doing the calculations yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With