Reputation: 4388
So I have an element that I want to be able to zoom in and out of using the scroll wheel on my mouse. I thought a good way to go about this would be something like this:
JavaScript:
var container = document.getElementById("container"),
zoom = document.getElementById("zoom");
var x = 0, lastScrollTop = 0;
const zoomWidth = zoom.getBoundingClientRect().width;
// I want the container to be the one that is targeted because
// sometimes the zoom element will be offset horizontally by too much
container.onscroll = function(e){
e.preventDefault();
var scrollTop = this.scrollTop;
x += (scrollTop < lastScrollTop ? 0.1 : -0.1);
zoom.style.width = (zoomWidth * x) + "px";
lastScrollTop = scrollTop <= 0 ? 0 : scrollTop;
}
HTML:
<div id="container">
<div id="zoom"></div>
</div>
The only problem with this is that you can't detect whether or not the user is scrolling up or down (or detect if the scroll wheel is being used at all for that matter), when the element itself doesn't scroll.
So how do I go about zooming using the scroll wheel, on an element that doesn't actually scroll? Cheers.
Upvotes: 0
Views: 173
Reputation: 2233
There is an event called wheel
you can attached a wheel event listener on the element
el.addEventListener('wheel', function(event){
//do your job here
});
available properties in wheel event
{
altKey: false
bubbles: true
button: 0
buttons: 0
cancelBubble: false
cancelable: true
clientX: 345
clientY: 154
composed: true
ctrlKey: false
currentTarget: div
defaultPrevented: false
deltaMode: 0
deltaX: -0
deltaY: -125
deltaZ: 0
detail: 0
eventPhase: 2
fromElement: null
isTrusted: true
layerX: 89
layerY: 61
metaKey: false
movementX: 0
movementY: 0
offsetX: 90
offsetY: 62
pageX: 345
pageY: 154
path: (5)[div, body, html, document, Window]
relatedTarget: null
returnValue: true
screenX: 822
screenY: 491
shiftKey: false
sourceCapabilities: null
srcElement: div
target: div
timeStamp: 171662.21500000005
toElement: div
type: "wheel"
wheelDelta: 150
wheelDeltaX: 0
wheelDeltaY: 150
which: 0
x: 345
y: 154
}
property deltaX , deltaY
are sufficient for calculating
There is a nice example in mdn check here
Upvotes: 1