2

ok... I might be a lazy one to search but it is a bit annoying that all I can find is

"how can i set scroll down event" when I searched "how do i prevent scroll down".

in my javascript code, I set event for down arrow key. When I press down arrow

from the browser, the browser not only does an event I set, but also does

scrolling down the page which is not I intended to. So here is my question.

How can I disable scroll down function which occurs when I press down arrow?

any help will be appreciated.

0

2 Answers 2

2

If you want to prevent the vertical scrollbar and any vertical scrolling action by the user, you can use this javascript:

document.body.style.overflowY = "hidden";​

Or, this can also be set with a CSS rule:

body {overflow-y: hidden;}

On the other hand, if what you're trying to do is to prevent the default key handler for the down arrow from doing anything after you process the down array, then you need to call e.preventDefault() like this:

function myKeyDownHandler(e) {
    // your code here
    e = e || window.event;
    if (e.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;   // older versions of IE (yuck)
    }
    return false;
}

A cleaner way if you need to do this in more than one place would be to make your own cross browser function for this:

function preventDefault(e) {
    e = e || window.event;
    if (e.preventDefault) {
        e.preventDefault();
    } else {
        e.returnValue = false;   // older versions of IE (yuck)
    }
}

function myKeyDownHandler(e) {
    // your code here
    preventDefault(e);
    return false;
}

This is one of those perfect examples where a cross-browser framework (jQuery/YUI/etc) saves you time because they've already done all this cross-browser work for you.

Here's an interesting article on preventDefault and stopPropagation().

Sign up to request clarification or add additional context in comments.

2 Comments

I don't think scrolling down the page without a scrollbar is what they want
@GoldenNewby - perhaps you're right. The question is a little ambiguous so I added a second option for that other interpretation.
1

Here is an example page that doesn't allow for the use of the arrow keys for scrolling:

<script>
document.onkeydown = function(evt) {
    evt = evt || window.event;
    var keyCode = evt.keyCode;
    if (keyCode >= 37 && keyCode <= 40) {
        return false;
    }
};
</script>
<body style="height:3000px;">

</body>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.