How to stop browser auto scrolling containers on focus changes

Gone Coding picture Gone Coding · Aug 29, 2013 · Viewed 7.7k times · Source

As you tab between input fields in a browser, the browser will automatically scroll the nearest parent container to place the next focused field within the view.

Simple JSFiddle: http://jsfiddle.net/TrueBlueAussie/pxyXZ/1/

$('.section').eq(6).find('input').focus();

For example if you open the above fiddle it selects "Sample item 7" at the bottom of the yellow window. If you press tab the "Sample text 8" field jumps up towards the middle of the parent window.

Obviously this is a great thing for normal websites, but I have a custom scrolling container in which I position & scroll everything manually. I am tracking focus changes and will use a momentum scroller to bring it into view, but how do I disable the default scrolling behavior of web-browsers? Happy to accept CSS, Javascript or JQuery solutions.

Answer

PlantTheIdea picture PlantTheIdea · Aug 29, 2013

This is just winging it based on my comment above:

$('input').on('keyup',function(e){
    if(e.keyCode === 9) {
        var $this = $(this);

        // (do your scroll thing here
        // ..., function(){
            $this.parent().next().find('input').focus();
        // });
    }
});

Long as the callback timing is correct, this will only change focus after you have already scrolled. You'll need to do your own magic to determine what to scroll to, but this should give you the focus behavior you want.