Prevent mouse wheel scrolling, but not scrollbar event. JavaScript - javascript

I need to make a webpage scrollable only by scrolling bar. I have tried to find how to catch scroll bar event, but as i see it is impossible. Currently i use this functions:
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
function wheel(e) {
preventDefault(e);
}
function disable_scroll() {
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', wheel, false);
}
window.onmousewheel = document.onmousewheel = wheel;
}
But they are not very useful in my situation, because they block all scroll events. Do you have any ideas? I am thinking about it 3 days already and i didn't find any answer (and questions also). Thanks!

Prevent the window from scrolling with mouse wheel:
As document level wheel event listeners are treated as Passive, we need to mark this event listener to be treated as Active:
window.addEventListener("wheel", e => e.preventDefault(), { passive:false })
If the content of a <div> (or other element) is scrollable, you can prevent it like this:
document.getElementById('{element-id}').onwheel = function(){ return false; }
More info about scrolling intervention and using passive listeners to improve scrolling performance.
Outdated Method:
window.onwheel = function(){ return false; } // Old Method
more info (thanks #MatthewMorrone)

jQuery solution to prevent window scrolling with mouse wheel:
$(window).bind('mousewheel DOMMouseScroll', function(event){ return false});
If you want to prevent scrolling with mouse wheel in a single DOM element, try this:
$('#{element-id}').bind('mousewheel DOMMouseScroll', function (e) { return false; });
The DOMMouseScroll event is used in Firefox, so you have to listen on both.

I'm currently using this and it works fine. Scrolling using the bar works fine, but mouse wheel won't work.
The reason i'm doing it this way is that I have custom code to scroll the way I want, but if don't add any code it will just don't scroll on wheel.
window.addEventListener('wheel', function(e) {
e.preventDefault();
// add custom scroll code if you want
}

Related

How to stop page scroll on mouse wheel interaction with input type=text [duplicate]

I need to make a webpage scrollable only by scrolling bar. I have tried to find how to catch scroll bar event, but as i see it is impossible. Currently i use this functions:
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
}
function wheel(e) {
preventDefault(e);
}
function disable_scroll() {
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', wheel, false);
}
window.onmousewheel = document.onmousewheel = wheel;
}
But they are not very useful in my situation, because they block all scroll events. Do you have any ideas? I am thinking about it 3 days already and i didn't find any answer (and questions also). Thanks!
Prevent the window from scrolling with mouse wheel:
As document level wheel event listeners are treated as Passive, we need to mark this event listener to be treated as Active:
window.addEventListener("wheel", e => e.preventDefault(), { passive:false })
If the content of a <div> (or other element) is scrollable, you can prevent it like this:
document.getElementById('{element-id}').onwheel = function(){ return false; }
More info about scrolling intervention and using passive listeners to improve scrolling performance.
Outdated Method:
window.onwheel = function(){ return false; } // Old Method
more info (thanks #MatthewMorrone)
jQuery solution to prevent window scrolling with mouse wheel:
$(window).bind('mousewheel DOMMouseScroll', function(event){ return false});
If you want to prevent scrolling with mouse wheel in a single DOM element, try this:
$('#{element-id}').bind('mousewheel DOMMouseScroll', function (e) { return false; });
The DOMMouseScroll event is used in Firefox, so you have to listen on both.
I'm currently using this and it works fine. Scrolling using the bar works fine, but mouse wheel won't work.
The reason i'm doing it this way is that I have custom code to scroll the way I want, but if don't add any code it will just don't scroll on wheel.
window.addEventListener('wheel', function(e) {
e.preventDefault();
// add custom scroll code if you want
}

How to generate mousewheel event in jQuery/Javascript?

I have web-page with two buttons, and when clicking on them I want to call mouse wheel up/down events. Not scrollTo or scrollBy - I need mousewheel.
How can I do this? Is it possible with jquery.mousewheel plugin or with usual Javascript?
The mouse wheel event is called 'onwheel' in modern browsers. Try triggering that one.
The following solution worked well for me
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.originalEvent.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#elem').bind('mousewheel', function(e){
if(e.originalEvent.wheelDelta < 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
You can't trigger the mouse wheel.
(no matter jQuery or php or something else web code can't do this)
If you want to trigger an event bind to mouse wheel.
Maybe you can try bind the same event to the button with scrollTo?
That's the same with mouse wheel.

How to prevent touchmove event move the background using jquery /javascript?

Currently I am developing a website for ipad Safari
I used
addEventListener('touchmove', function(e) { e.preventDefault(); }, true);
to prevent the background moving when dragging the content. The problem is when I allow some element to drag
addEventListener('touchmove', function(e) {
//alert (e.target.id);
if ( e.target.className != 'issues' && e.target.id != 'dialog' && e.target.id != 'issuesBox')
e.preventDefault();
return false;
}, true);
when I drag the element, it will drag the background too , how to fix this problem? I observe that this problem may caused by taphold ,Thanks.
Are you trying to prevent scroll on some element? Prevent default of both touchstart and touchmove events then. Here's doc from apple.
In my experience, prevent default on touchstart event is enough, e.g.,
$(document).on('touchstart', function (evt) {
evt.preventDefault();
});

Javascript: Capture mouse wheel event and do not scroll the page?

I'm trying to prevent a mousewheel event captured by an element of the page to cause scrolling.
I expected false as last parameter to have the expected result, but using the mouse wheel over this "canvas" element still causes scrolling:
this.canvas.addEventListener('mousewheel', function(event) {
mouseController.wheel(event);
}, false);
Outside of this "canvas" element, the scroll needs to happen. Inside, it must only trigger the .wheel() method.
What am I doing wrong?
You can do so by returning false at the end of your handler (OG).
this.canvas.addEventListener('wheel',function(event){
mouseController.wheel(event);
return false;
}, false);
Or using event.preventDefault()
this.canvas.addEventListener('wheel',function(event){
mouseController.wheel(event);
event.preventDefault();
}, false);
Updated to use the wheel event as mousewheel deprecated for modern browser as pointed out in comments.
The question was about preventing scrolling not providing the right event so please check your browser support requirements to select the right event for your needs.
Updated a second time with a more modern approach option.
Have you tried event.preventDefault() to prevent the event's default behaviour?
this.canvas.addEventListener('mousewheel',function(event){
mouseController.wheel(event);
event.preventDefault();
}, false);
Keep in mind that nowadays mouswheel is deprecated in favor of wheel, so you should use
this.canvas.addEventListener('wheel',function(event){
mouseController.wheel(event);
event.preventDefault();
}, false);
Just adding, I know that canvas is only HTML5 so this is not needed, but just in case someone wants crossbrowser/oldbrowser compatibility, use this:
/* To attach the event: */
addEvent(el, ev, func) {
if (el.addEventListener) {
el.addEventListener(ev, func, false);
} else if (el.attachEvent) {
el.attachEvent("on" + ev, func);
} else {
el["on"+ev] = func; // Note that this line does not stack events. You must write you own stacker if you don't want overwrite the last event added of the same type. Btw, if you are going to have only one function for each event this is perfectly fine.
}
}
/* To prevent the event: */
addEvent(this.canvas, "mousewheel", function(event) {
if (!event) event = window.event;
event.returnValue = false;
if (event.preventDefault)event.preventDefault();
return false;
});
This kind of cancellation seems to be ignored in newer Chrome >18 Browsers (and perhaps other WebKit based Browsers). To exclusively capture the event you must directly change the onmousewheel method of the element.
this.canvas.onmousewheel = function(ev){
//perform your own Event dispatching here
return false;
};
Finally, after trying everything else, this worked:
canvas.addEventListener('wheel', (event) => {
// event.preventDefault(); Not Working
// event.stopPropagation(); Not Working
event.stopImmediatePropagation(); // WORKED!!
console.log('Was default prevented? : ',event.defaultPrevented); // Says true
}, false)
To prevent the wheel event, this worked for me in chrome -
this.canvas.addEventListener('wheel', function(event) {
event.stopPropagation()
}, true);

JavaScript on iOS: preventDefault on touchstart without disabling scrolling

I am working with JavaScript and jQuery in an UIWevView on iOS.
I'v added some javascript event handler that allow me to capture a touch-and-hold event to show a message when someone taps an img for some time:
$(document).ready(function() {
var timeoutId = 0;
var messageAppeared = false;
$('img').on('touchstart', function(event) {
event.preventDefault();
timeoutId = setTimeout(function() {
/* Show message ... */
messageAppeared = true;
}, 1000);
}).on('touchend touchcancel', function(event) {
if (messageAppeared) {
event.preventDefault();
} else {
clearTimeout(timeoutId);
}
messageAppeared = false;
});
});
This works well to show the message. I added the two "event.preventDefault();" lines to stop imgs inside links to trigger the link.
The problem is: This also seems to prevent drag events to scroll the page from happen normally, so that the user wouldn't be able to scroll when his swipe happens to begin on an img.
How could I disable the default link action without interfering with scrolling?
You put me on the right track Stefan, having me think the other way around. For anyone still scratching their head over this, here's my solution.
I was trying to allow visitors to scroll through images horizontally, without breaking vertical scrolling. But I was executing custom functionality and waiting for a vertical scroll to happen. Instead, we should allow regular behavior first and wait for a specific gesture to happen like Stefan did.
For example:
$("img").on("touchstart", function(e) {
var touchStart = touchEnd = e.originalEvent.touches[0].pageX;
var touchExceeded = false;
$(this).on("touchmove", function(e) {
touchEnd = e.originalEvent.touches[0].pageX;
if(touchExceeded || touchStart - touchEnd > 50 || touchEnd - touchStart > 50) {
e.preventDefault();
touchExceeded = true;
// Execute your custom function.
}
});
$(this).on("touchend", function(e) {
$(this).off("touchmove touchend");
});
});
So basically we allow default behavior until the horizontal movement exceeds 50 pixels.
The touchExceeded variable makes sure our function still runs if we re-enter the initial < 50 pixel area.
(Note this is example code, e.originalEvent.touches[0].pageX is NOT cross browser compatible.)
Sometimes you have to ask a question on stack overflow to find the answer yourself. There is indeed a solution to my problem, and it's as follows:
$(document).ready(function() {
var timeoutId = 0;
$('img').on('touchstart', function(event) {
var imgElement = this;
timeoutId = setTimeout(function() {
$(imgElement).one('click', function(event) {
event.preventDefault();
});
/* Show message ... */
}, 1000);
}).on('touchend touchcancel', function(event) {
clearTimeout(timeoutId);
});
});
Explanation
No preventDefault() in the touch event handlers. This brings back scrolling behavior (of course).
Handle a normal click event once if the message appeared, and prevent it's default action.
You could look at a gesture library like hammer.js which covers all of the main gesture events across devices.

Categories

Resources