How can I prevent scrolling down in javascript?
ok ... I might be lazy to search, but it's a little annoying that all I can find is
"how can I set a scroll down event" when I was looking for "how can I prevent scrolling down".
in my javascript code, I am setting an event for the down arrow key. When I press the arrow
from the browser, the browser not only sets the event I have set, but it also executes
scrolling a page I didn't plan on. Here's my question.
How can I disable the scroll down feature that appears when I click the down arrow?
any help would be appreciated.
source to share
If you want to prevent vertical scrollbar and any vertical scroll action by the user, you can use this javascript:
document.body.style.overflowY = "hidden";
Or, this can also be set using a CSS rule:
body {overflow-y: hidden;}
On the other hand, if what you are trying to do is to prevent the default down arrow key handler from being used when doing anything after processing 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 it in more than one place, is to make your own cross-browser function to do 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 great examples where a cross-browser environment (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()
.
source to share