I am making form validation and when user doesn't fill one of required fields I want position of the page to focus on that input but I don't want input field to be directly to the top of the browser frame, I want to leave some space between so that title of input form can also be seen.
This is how it looks with focus()
only
but I want it like this:
The idea is to keep typing cursor focused on input field.
EDIT: If it's possible to use animated focus that would be awesome. Are there any suggestions how to do that?
One way using jQuery: scroll the window to the vertical offset of the label.
$(function(){
$(window).scrollTop($("label").offset().top);
$("input").focus();
});
Or scroll to the input element with some additional margin:
$(function(){
$(window).scrollTop($("input").offset().top - 100);
$("input").focus();
});
(Note: replace "input" and "label" with the proper selector)
Well lets make the assumption that you want to make sure that the label tag is visible too...
$.fn.smoothFocus = function(offset) {
//Find the label first:
var $labels = $(this).parent().filter("label");
if ($(this).attr('id'))
//Find labels that have a for= attributes.
$labels.add("label[for=" + $(this).attr("id") +"]");
//Find the top most label:
var top = $(this).offset().top;
$labels.each(function() {
var currentTop = $(this).offset().top;
if (currentTop < top)
top = currentTop;
});
$(window).scrollTop(top - offset);
$(this).focus();
};
$(".myfield").smoothFocus(10); //Sets focus to be 10px above to respective label.
This way you can have pretty robust way of getting the focus right. I didn't test it though.
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