0

I have a code where I can move an object by mouse:

<html>
<head>
    <style>
    #container {
        position:absolute;
        width: 60px;
        height: 40px;
        top:50px;
        left:50px;
        background-color:green;
    }
    </style>
    <script>
        mydragg = function(){
                return {
                    startMoving : function(divid, evt) {
                        evt = evt || window.event;
                        var diffX = evt.clientX - divid.offsetLeft,
                            diffY = evt.clientY - divid.offsetTop;

                        document.onmousemove = function(evt) {
                            evt = evt || window.event;
                            divid.style.left = evt.clientX - diffX + 'px';
                            divid.style.top  = evt.clientY - diffY + 'px';
                        }
                    },
                    stopMoving : function() {
                        document.onmousemove = null;
                    },
                }
        }();
    </script>
</head>
<body>
    <div id='container' onmousedown='mydragg.startMoving(this, event);' onmouseup='mydragg.stopMoving();'></div>
</body>
</html>

It works, but I need more - inertia - when I do "mouseup" DIV must continue to move a little, according to the previous movement's speed. An example could be Google Maps - you move a map with inertia.

I need the same with pure JavaScript functions (no jQuery, no interact.js or something 3'rd partly like that).

If you can - you can modify the code to use "transform" instead of "style.left/top", because performance and looking good is the most important thing.

Can you help to add inertia's code?

5
  • 1
    What have you attempted so far?
    – Mike Cluck
    Feb 12, 2016 at 23:20
  • I've tried to calculate dX and dY (something we can call speed) and then in a loop to change DIV's position by dY/dX (and decreasing dX/dY until "1" or "0") - but it looks horrible and I'm sure it is wrong
    – alexoy
    Feb 12, 2016 at 23:22
  • 1
    Your idea is basically correct. I followed an article by Ariya Hidayat to implement something similar.
    – Mike Cluck
    Feb 12, 2016 at 23:24
  • It's just a matter of mass, velocity and retarding-force (friction).Wiki will have the relevant equations, which I've long ago forgotten.
    – enhzflep
    Feb 12, 2016 at 23:38
  • @MikeC, I've tried to implement inertia from scrolling script.. unfortunately it works too slow. There are too many calculations all the time while a mouse is down, and every 100ms many global variables are recalculated. I need something more lightweight
    – alexoy
    Feb 16, 2016 at 19:47

0

Your Answer

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

Browse other questions tagged or ask your own question.