In my JS
code, I've added a EventListener
on mousemove
& touchmove
, which makes it so that my div
follows the cursor
. (as such)
CSS:
<style>
body {
padding: 0;
margin: 0;
height: 100vh;
background: linear-gradient(135deg, #8fc7f1, #7173f5);
overflow: hidden;
}
#my-div {
width: 300px;
height: 250px;
background-color: #ffffff;
position: absolute;
}
</style>
HTML:
<div id="my-div">
<h1>Hello</h1>
</div>
JAVASCRIPT:
let myDiv = document.getElementById("my-div");
//Detect touch device
function isTouchDevice() {
try {
//We try to create TouchEvent. It would fail for desktops and throw error
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
}
const move = (e) => {
//Try, catch to avoid any errors for touch screens (Error thrown when user doesn't move his finger)
try {
//PageX and PageY return the position of client's cursor from top left of screen
var x = !isTouchDevice() ? e.pageX : e.touches[0].pageX;
var y = !isTouchDevice() ? e.pageY : e.touches[0].pageY;
} catch (e) {}
//set left and top of div based on mouse position
myDiv.style.left = x - 150 "px";
myDiv.style.top = y - 120 "px";
// myDiv.style.opacity = 0;
// console.log(myDiv.getBoundingClientRect())
};
//For mouse
document.addEventListener("mousemove", (e) => {
move(e);
console.log("Mouse")
});
//For touch
document.addEventListener("touchmove", (e) => {
move(e);
});
What I'm trying to do is to add a iframe
inside my div
and the div
should still follow the cursor
, but when I add the iframe
inside the div
, then the EventListener
stops working and my div
stops following the cursor. I'm not sure what the issue is. (as such)
<div id="my-div">
<iframe src="https://example.com/" width="300" height="250">
</div>
Any help and suggestion is appreciated!
CodePudding user response:
You forgot the closing iframe
tag
<div id="my-div">
<iframe src="https://example.com/" width="300" height="250"></iframe>
</div>
CodePudding user response:
I think you should change the position of your div to relative and the position of your iframe to absolute.