sergdenisov
sergdenisov

Reputation: 8572

Prevent default scroll to element for input

Can I prevent default scroll top to input when it's focused and not visible? Simple example:

<input type="search">
<div style="height: 2000px"></div>

To see what I mean, go to http://jsfiddle.net/PV5tC/ and:

  1. Click on input to make it focused.
  2. Scroll down to the end of the page (input is not visible now).
  3. Start typing anything.

Upvotes: 2

Views: 4565

Answers (3)

user3415926
user3415926

Reputation: 46

This is maybe antipattern but this should work. Info here: Disable scrolling when changing focus form elements ipad web app

$('input[type="search"]').on("keydown", function(){
  var oldScroll = $(window).scrollTop();
  $(window).one('scroll', function() {
    $(window).scrollTop(oldScroll);
  });
  // Your ACTION HERE
})

Upvotes: 1

Kaiido
Kaiido

Reputation: 136638

position : fixed; will avoid the automatic scroll to input as it won't be in the scrollable area.

Here is a fast written example, based on this answer, and using jQuery, sorry…

CSS

.hiddenInput{position: fixed; opacity: 0;}

jQuery

    var inputTop, inputBottom;
    window.onload = function()
    {
        inputTop = $('#input').offset().top
        inputBottom = inputTop + $('#input').height();
    }

    function isScrolledIntoView(el)
    {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();
        return ((inputBottom <= docViewBottom) && (inputTop >= docViewTop));
    }
    function hideInput()
    {
        var el = $('#input');
        if ( isScrolledIntoView(el) ){
            el.removeClass();
            }else{
            el.addClass('hiddenInput');
            el.css({top: inputTop});
        }
    }
    window.onscroll = hideInput;

working fiddle

Upvotes: 2

khagesh
khagesh

Reputation: 948

I also cannot think of this as good design. But we all have to do something our way. Try below script if it helps

$('input[type="search"]').on("keypress", function(event){
    event.preventDefault();
    return false;
});

This will allow to keep focus on input box and browser will also not scroll to input box. If you want it cross browser you might need to handle keydown event as well. Let me know if you face any issue in handling other events.


But it will prevent you from typing any value in the input at any moment in any input : then blur is easier

Upvotes: 0

Related Questions