JSFiddle - React, Tailwind, and code Playground
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Div following mouse cursor inside a parent</title>
</head>
<body>
<div id="parent_div">
<div id="div_moving"></div>
</div>
</body>
</html>
CSS
#parent_div {
position: relative;
width: 50%;
height: 300px;
margin: 1em auto;
border: 1px solid #333;
background: #f0f0f0;
}
#div_moving {
display:none;
position: absolute;
width: 100%;
height: 5px;
margin: 0;
background: blue;
}
JavaScript
var div_moving = document.getElementById('div_moving');
var parent_div = 'parent_div';
var movingDiv = {
getCoords: function(e) {
var rect = e.target.getBoundingClientRect();
var y_pos = rect.top;
console.log(y_pos);
var y = e.pageY;
y = y - y_pos;
return (y);
}
};
document.getElementById(parent_div).addEventListener('mousemove', function(e){
result = movingDiv.getCoords(e);
div_moving.style.top = result +'px';
div_moving.style.display = "initial";
});
document.getElementById(parent_div).addEventListener('mouseleave', function(){
div_moving.style.display = "none";
});