Last active
May 14, 2019 08:15
-
-
Save justlstn/4ea826234d1e6e8033d3e7d4b1965527 to your computer and use it in GitHub Desktop.
Returns an object with coors that you can use for CSS transition { top, left }
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const getOffset = (e, offset = 3, isCentered = true) => { | |
const pageX = e.pageX | |
const pageY = e.pageY | |
const scrollTop = window.pageYOffset // To remove a {scrollTop} from the {pageY} | |
const winWidth = window.innerWidth | |
const winHeight = window.innerHeight | |
const centerTop = winHeight / 2 | |
const centerLeft = winWidth / 2 | |
const onePercentWidth = centerLeft / offset | |
const onePercentHeight = centerTop / offset | |
const percentsLeft = offset - pageX / onePercentWidth | |
const percentsTop = offset - (pageY - scrollTop) / onePercentHeight | |
const top = isCentered ? -50 + Number(percentsTop.toFixed(2)) : Number(percentsTop.toFixed(2)) | |
const left = isCentered ? -50 + Number(percentsLeft.toFixed(2)) : Number(percentsLeft.toFixed(2)) | |
return { | |
top, | |
left | |
} | |
} | |
// How to use it (with jQuery but it isn't necessary): | |
$(document.body).on('mousemove', onMouseMove) | |
function onMouseMove (e) { | |
const coords = getOffset(e, 1.5) | |
$('.block').css({ | |
transform: `translate(${coords.left}%, ${coords.top}%)` | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment