JSFiddle - React, Tailwind, and code Playground
by NexusDeveloper
HTML
<body>
<div class="dragscroll">
<div class="item move"></div>
<div class="item move"></div>
</div>
</body>
CSS
body{
width:100%;
height:100%;
margin: 0;
padding:0;
}
.dragscroll{
width:100vw;
height:100vh;
background-color: black;
display: block;
position:relative;
overflow:hidden;
}
div.item{
position: absolute;
display: block;
width:20px;
height:20px;
background-color:white;
}
.dragscroll div.move:first-child {
left: 150px;
top: 150px;
}
.dragscroll div.move:last-child {
left: 500px;
top:200px;
}
JavaScript
var min = -50;
var max = 50;
var speed = 20;
var getAnimationDurationByDistance = function(distanceInPixels) {
return Math.abs(distanceInPixels) * speed;
};
window.setInterval(function() {
$('.dragscroll div.item.move ').each(function() {
var randomw = Math.floor(Math.random() * (max - min + 1)) + min;
var randomh = Math.floor(Math.random() * (max - min + 1)) + min;
var left = parseInt($(this).css("margin-left"));
var top = parseInt($(this).css("margin-top"));
if ((left >= min) && (left <= max)) {
$(this).css({
'margin-left': left + 'px'
}).animate({
'margin-left': (left + randomw) + 'px'
}, getAnimationDurationByDistance(randomw));
} else {
$(this).css({
'margin-left': left + 'px'
}).animate({
'margin-left': 0 + 'px'
}, getAnimationDurationByDistance(left));
}
if ((top >= min) && (top <= max)) {
$(this).css({
'margin-top': top + 'px'
}).animate({
'margin-top': (top + randomh) + 'px'
}, getAnimationDurationByDistance(randomh));
} else {
$(this).css({
'margin-top': top + 'px'
}).animate({
'margin-top': 0 + 'px'
}, getAnimationDurationByDistance(top));
}
});
}, Math.abs(min - max) * speed);