Disable mouse movement for Vanilla-tilt.js but keep gyroscope effect

Viewed 654

I'm using the plugin Vanilla-tilt.js and on desktop it works great. On mobile the tilt effect responds to the device orientation which is great, but when the user taps somewhere on their device it makes the tilt areas jerk towards where the tap was then return to their original position. I'm using Chrome on Android, feel free to try it yourself with the link above.

I'd like to keep the gyroscope effect on mobile but disable user taps from affecting the tile position. I'm using the inline configuration, here's an example:

<div data-tilt data-tilt-full-page-listening data-tilt-reset="false">Tilt object goes here</div>

My first thought is to download the vanilla-tilt.js source code and modify it so it only looks for mouse events if the screen is a certain width. I don't mind switching to the jQuery version, Tilt.js if that makes this easier.

I built a minified code example that you can view here.

2 Answers

I think you could use something like this document.body.style.pointerEvents = 'none', I am unable to test it though, as I am on PC.

I just noticed that in case of a "tap" the event.movementX and event.movementY are equal to zero, so I believe an easy solution would require to slightly adapt the onMouseMove function, something like this:

onMouseMove(event) {
  if(event.movementX == 0 && event.movementY == 0) return false;
  if (this.updateCall !== null) {
    cancelAnimationFrame(this.updateCall);
  }
  this.event = event;
  this.updateCall = requestAnimationFrame(this.updateBind);
}

In Your example, You are using the built-in autoinitialization. There is more work, this would require to monkey-patch the already attached listeners. Here is how I did it, as a proof of concept:

(function() {
    var elements = document.querySelectorAll("[data-tilt]");
    elements.forEach(function(item, index){
        function onMouseMove(event) {
            if(event.movementX == 0 && event.movementY == 0) return false;
            if (this.updateCall !== null) {
              cancelAnimationFrame(this.updateCall);
            }
            this.event = event;
            this.updateCall = requestAnimationFrame(this.updateBind);
        }
        var tiltObj = item.vanillaTilt;
        tiltObj.elementListener.removeEventListener("mousemove", tiltObj.onMouseMoveBind);      
        tiltObj.onMouseMoveBind = onMouseMove.bind(tiltObj);
        tiltObj.elementListener.addEventListener("mousemove", tiltObj.onMouseMoveBind);
    });     
})();

Just to be sure, I tested this hotfix with Your minified test-case and with the vanilla-tilt home page and it seems working, but the final solution may vary, depending from Your implementation.

Please, test it in Your mobile device and let me know.

Related