DEV Community

muhis071800
muhis071800

Posted on

Change element scale by scroll on parent (zoom by scroll on parent)

I'm trying to add scaling by mouse scroll , but so far not so good, I'm somehow failing to place the scaled element (in this case id: test) correctly

const ts = {
        scale: 1,
        rotate: 0,
        translate: {
            x: 0,
            y: 0
        }
    };



  var parent =  document.querySelector('#parent');

    parent.addEventListener("wheel", 
     (event) => {
     event.preventDefault();
        let xs = (event.clientX - ts.translate.x) / ts.scale;
        let ys = (event.clientY - ts.translate.y) / ts.scale;


        let delta = (event.wheelDelta ? event.wheelDelta : -event.deltaY);


        ts.scale = (delta > 0) ? (ts.scale * 1.03) : (ts.scale / 1.03);


         ts.translate.x = event.clientX - xs * ts.scale;
         ts.translate.y = event.clientY - ys * ts.scale;
        setTransform();
    }
    ,true);
    function setTransform() {
        const steps = `translate(${ts.translate.x}px,${ts.translate.y}px) scale(${ts.scale})`;
        test.style.transform = steps;
    }
#parent {
height:900px; 
width:100%; 
border:1px solid #000000;
background-color:gray;
overflow: hidden;
} 

#test {
max-width: 100px;
max-height: 100px;
min-height: 100px;
min-width:100px;
background-color:pink;
position:relative;
}
    <div id="parent" >
        <div id="test"></div>
    </div>
Enter fullscreen mode Exit fullscreen mode

https://jsfiddle.net/3uhy46dv/

what I'm doing wrong?

this is what it should be like. https://postimg.cc/k28x2DsB

Top comments (0)