disable scrolling on input focus in javascript

I was wondering if it was possible to stop the page from scrolling using javascript when a user type or clicks on a <input type="text"></input>

Answers


So I figured out how to accomplish this, and I will leave this as a record for anyone else who needs to solve this problem. (NOTE : this solution has only been tested on safari and Firefox)

for:

<input id="text" type="text" />

the function

document.getElementById('text').onkeydown = new function(event){return false}

Will not cause the window to shift the scroll so that a user can see the input field when he types into the field. If like me you want this to happen for some letters but not for others simply edit the contents of the onkeydown function so that it returns false for certain keycodes and true for others.


I faced up with similar problem. Try to use following solution: subscribe on focus event, disable window scroll in it's handler and turn scroll on by timeout.

I know solution seems not very clean, but demo looks nice, without visual defects.

$(function() {
    var oldScroll = window.onscroll;
    $(document).on('focus', 'input', function(e) {
        window.onscroll = function () { 
            window.scroll(0,0); 
        } ;
        setTimeout(function() {
            window.onscroll = oldScroll;
        }, 100);
    });

});

http://jsfiddle.net/N4da4/8/


You could possibly set the scrollTop property to x every n milliseconds. The problem with that approach I would think would be that the page would look jerky (technical term) when the user attempted to scroll the page.

Besides, you'd be breaking the expectations of the user that they be able to scroll the page at any time which I would recommend against as it could confuse them at best and annoy them at worst.


Need Your Help

A floating div issue

css3 html floating

I have built a site, but now there needs to be some changes. There is a main picture on the left and a varying bunch of thumbnails aligned on its right floating against the big picture. I want to e...

viewbag contains sorted list but not reflected in view

c# asp.net-mvc linq sorting razor

In my view(.cshtml) i am getting viewbag with list elements.and this list elements are already sorted from where it comes from(controller).During runtime i put break point and i can see viewbag con...