Here is the sample vanilla JS code snippet to achieve mouse follow motion effect. It is easy to adjust absolute position via “data-x” and “data-y” value and easy adjust speed value via ” data-speed”.
How to use:
Set parent element position to relative. Then apply class name “.motion-element” at the element you want that effect. Then go to STYLE > ATTRIBUTES
Set below attribute names and values. Adjust the values to achieve your desire level :
Name : data-speed , Value : 0.5
Name: data-x , Value : 0
Name: data-y , Value: 500
HTML example for attribute values set ( you don’t need to copy this code) :
<div class="motion-element" data-speed="0.5" data-x="0" data-y="500">Motion Element - 1</div>
<div class="motion-element" data-speed="1" data-x="300" data-y="100">Motion Element - 2 </div>
<div class="motion-element" data-speed="0.2" data-x="100" data-y="200">Motion Element - 3 </div>
Copy and paste below snippet to bricks code block element :
<style>
.motion-element {
position: absolute;
top: 0;
left: 0;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
var floatingElements = document.querySelectorAll(".motion-element");
floatingElements.forEach(function(element) {
var speed = parseFloat(element.getAttribute("data-speed"));
var initialX = parseFloat(element.getAttribute("data-x"));
var initialY = parseFloat(element.getAttribute("data-y"));
document.addEventListener("mousemove", function(event) {
var mouseX = event.clientX;
var mouseY = event.clientY;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var xPos = initialX + (mouseX / windowWidth) * 100 * speed;
var yPos = initialY + (mouseY / windowHeight) * 100 * speed;
element.style.transform = "translate(" + xPos + "px, " + yPos + "px)";
});
});
});
</script>