Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus on input with top margin

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
enter image description here

but I want it like this:
enter image description here

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?

like image 913
ilija veselica Avatar asked Feb 28 '12 22:02

ilija veselica


2 Answers

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)

like image 192
Andre Loker Avatar answered Sep 16 '22 13:09

Andre Loker


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.

like image 45
d_inevitable Avatar answered Sep 16 '22 13:09

d_inevitable