Giter Club home page Giter Club logo

universal-tilt.js's Introduction

NPM version NPM downloads

About

JavaScript & jQuery elements movement library based on:

Tilt.js by Gijs Rogé and vanilla-tilt.js by Șandor Sergiu

universal-tilt.js contains additional functions for mobile devices with gyroscope, new Position Base option and more!

Demo

See plugin in action

React plugin

If you use React, install component with the implementation of the universal-tilt.js library! More here

How to Install

First, install the library in your project by npm:

$ npm install universal-tilt.js

Or Yarn:

$ yarn add universal-tilt.js

You can also connect script via one of CDNs:
bundle.run: https://bundle.run/universal-tilt.js
jsDelivr: https://cdn.jsdelivr.net/npm/universal-tilt.js/
unpkg: https://unpkg.com/universal-tilt.js/

Getting Started

Connect libary with project using script tag in HTML:

<script src="/path/to/universal-tilt.js"></script>

ES6 import:

import UniversalTilt from 'universal-tilt.js';

Or CommonJS:

const UniversalTilt = require('universal-tilt.js');

Next use library with:

β€’ Vanilla JavaScript e.g:

const elems = document.querySelectorAll('.tilt');

const tilt = UniversalTilt.init({
  elements: elems,
  settings: {
    // options...
  },
  callbacks: {
    // callbacks...
  }
});

β€’ or jQuery e.g:

Connect jQuery in HTML

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>

Or include via command line and CommonJS

$ npm install jquery
$ yarn add jquery
$ bower install jquery
const jQuery = require('jquery');

And call plugin on element

$('.tilt').universalTilt({
  settings: {
    // options...
  },
  callbacks: {
    // callbacks...
  }
});

β€’ Plugin supports autoinit

To use it, add data-tilt to html element e.g:

<div data-tilt></div>

Methods

β€’ Destroy method

elems.universalTilt.destroy();

β€’ Get values method

elems.universalTilt.getValues();

β€’ Reset method

elems.universalTilt.reset();

Options

Settings

Name Type Default Description Available options
base string element The surface from which the location of the mouse is captured element or window
disabled string null Disable axis x or y
easing string cubic-bezier(.03, .98, .52, .99) Transition easing cubic-bezier/ease/linear/etc.
exclude RegExp null Disable tilt effect on selected user agents e.g: /(Firefox|iPad)/
max number 35 Max tilt value e.g: 28
perspective number 1000 Tilt effect perspective e.g: 700
reset boolean true Enable/disable element position reset after mouseout true (enable), false (disable)
reverse boolean false Reverse tilt effect directory true (reverse directory), false (standard directory)
scale number 1.0 Element scale on mouseover 0.9/1.3/etc.
shine boolean false Add/remove shine effect on mouseover true (add), false (remove)
shine-opacity1 number 0 Add/remove shine effect on mouseover values >= 0 and <= 1
shine-save1 boolean false Save/reset shine effect on mouseout true (save), false (reset)
speed number 300 Transition speed (ms) e.g: 500

Callbacks

Name Description Available options
onDestroy Callback on plugin destroy el => { /* code */ }
onDeviceMove2 Callback on device move el => { /* code */ }
onInit Callback on plugin init el => { /* code */ }
onMouseEnter Callback on mouse enter el => { /* code */ }
onMouseLeave Callback on mouse leave el => { /* code */ }
onMouseMove Callback on mouse move el => { /* code */ }

1 shine value must be true
2 only for devices supported device motion

Event

tiltChange event will output the x, y & angle of tilting

License

This project is licensed under the MIT License Β© 2018-present Jakub Biesiada

universal-tilt.js's People

Contributors

dependabot[bot] avatar jb1905 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

universal-tilt.js's Issues

Allow interaction in gyroscope mode on touch devices.

It would be awesome if the tilt would also respond to touchstart and touchmove events by tilting when moving the finger over the element or tapping it and then restore back to the gyro position once the finger is lifted.

Basically allow an override of the position if the element is being touched while in gyro mode.

Scale not transitioning smoothly while mouse moves.

So the bug I am currently experiencing is that when I enter an object which has the scale option, it only scales in a smooth manner if I leave my mouse completely still as the transition occurs. If I continue to move my mouse as the transition is occurring, the scale will not occur at all, and then once the allotted time has passed (set by speed option) the animation jumps to completed, and the item grows to full size with no transition played at all. I will attempt to get a screencast gif later tonight when I am home from work.

I have forked the repository and had a peek at the code. I am currently at work so I do not have much time available to me but I believe I have found the issue. When I am home from work tonight, I will attempt to fix it if it is not fixed by you already by then. I am only a beginning coder though, so perhaps I will be unable to fix it.

anyways, what I believe is the issue is the combination of onMouseMove() and update() which updates scale 3d. I think if you continue to move the mouse fast enough, it just keeps updating the scale to the same size because onMouseMove() is constantly being called before the transition has enough time to take effect.

What I planned to do is move the scale portion into it's own function called updateScale() and only call that on onMouseEnter and onMouseLeave.

  onMouseMove(e) {
    // set event
    this.event = e;
    this.updateElementPosition();


    window.requestAnimationFrame(() => this.update());   <======================

    if (typeof this.settings.onMouseMove === 'function')
      this.settings.onMouseMove(this.element);
  }

and

update() {
    const values = this.getValues();

    this.element.style.transform = `perspective(${this.settings.perspective}px)
      rotateX(${
        this.settings.disabled && this.settings.disabled.toUpperCase() === 'X'
          ? 0
          : values.tiltY
      }deg)
      rotateY(${
        this.settings.disabled && this.settings.disabled.toUpperCase() === 'Y'
          ? 0
          : values.tiltX
      }deg)
      scale3d(${this.settings.scale}, ${this.settings.scale}, ${     <=========
      this.settings.scale                                            <=========
    })`;

    if (this.settings.shine) {
      Object.assign(this.shineElement.style, {
        transform: `rotate(${values.angle}deg) translate3d(-50%, -50%, 0)`,
        opacity: `${this.settings['shine-opacity']}`
      });
    }

    // tilt position change event
    this.element.dispatchEvent(
      new CustomEvent('tiltChange', {
        detail: values
      })
    );
  }

Uncaught TypeError: UniversalTilt.init is not a function

Receiving an error -
" Uncaught TypeError: UniversalTilt.init is not a function "
when using this approach -
// v2
const tilt = UniversalTilt.init({
elements: elems,
settings: {
// options...
},
callbacks: {
// callbacks...
}
});

Global is not defined

HI, i have added universal-tilt.min.js but it says Uncaught ReferenceError: global is not defined at universal-tilt.min.js:1

i have use jQuery v3.3.1. Can you help please?

UniversalTilt is not a constructor

Receiving an error -
"Uncaught TypeError: UniversalTilt is not a constructor "
when using VanillaJs approach
// v1
const tilt = new UniversalTilt(elems, {
// options...
});

Mobile device flat on surface to get tilt position 0

Hi

I found the issue that the physical tilt of the device triggers the tilt only works when the mobile device is flat on a surface. Since a phone or a tablet is usually not in that position when the script is loaded I would suggest to define the first position you get from the gyro lib to be set as the 0 of the tilt. I think instead of an absolute 0, its a relative to the starting point. If that makes sense πŸ‘

Love your fork of the original lib!

Kind regards
Jonas Gredig

Add tilt effect with full page listening

with the original js libraries, it is possible to add "data-tilt-full-page-listening", then the tilt effect is used always and not only if someone is over the tilted object.
Is this feature on the roadmap or ist it in the actual implementation not possible to add?
thx!
I really like the gyro effect btw!

Feature request: enhancements to base=window

With base=window, currently all tilting elements on the page move completely in unison, regardless of where they are in relation to the cursor. It would be great if an option(s) could be added so

  1. the amount of tilt applied to a given element decreases as the cursor moves further away from that element
  2. the angle of each element is unique so each one tilts towards/away from the cursor
  3. the scale effect is decoupled from the tilt to allow for the scale only being applied when the cursor is over each specific element

These options combined could make for some really unique effects when dealing with multiple tilting elements on a single page

5 cents to nice plugin

Hi there. Playing around find some good things to add

             key: "getValues",
              value: function getValues() {
                var x, y;
                **var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);**
                if (this.isMobile()) {
                  **if (isSafari == true) {
                    x = this.event.accelerationIncludingGravity.x / -4;
                    y = this.event.accelerationIncludingGravity.y / 4;**
                    } else {
                      x = this.event.accelerationIncludingGravity.x / 4;
                      y = this.event.accelerationIncludingGravity.y / -4;
                    }                    
                  var stateX, stateY;

This makes equal behavior on iPhones and Android devices. I guess -4 makes right movement depends on device orientation.

'background-image': 'radial-gradient(circle at bottom center, rgba(252,253,255,1) 20%,rgba(255,255,255,0) 60%)', parameters for shine gradient looks better for me.

Also it will be great to move the card by finger on mobile in addition to device orientation movement. And filter acceleration data of course lol.

And finally small question. I didn't get easing for shine rotation. It was possible to make it in previous versions (like in demo page). But now it unfortunately does not work. Quick shine rotation on mobile absolutely not cool and looks glitching.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.