Skip to content
Advertisement

Get the click position of the mouse on a page with iframe

I have an HTML page and I want to get the position of the mouse. I do this :

document.onclick = function(click) {
if (click.clientX<340){
    myControl.inputs.selection = false;
    btnRotate.remove();
    btnMove.remove();
    clicked = false;
}
 console.log("Coordonnee point X="+click.clientX+" Y="+click.clientY)
};

But I have an Iframe and when I click on it, I don’t get the position. Do you have an idea ? Thank you

Advertisement

Answer

Here I am using Host listener (mousemove) for getting mouse position in the document with JavaScript as below:

document.addEventListener(‘mousemove’, (event) => { console.log(Mouse X: ${event.clientX}, Mouse Y: ${event.clientY}); });

FOR IFRAME:—–

Add id to the Iframe and Get it to add mousemove listener and get coords from event. it will work for you.

let iframeElement = document.getElementById(‘iframe’);

iframeElement.contentDocument.body.addEventListener(‘mousemove’, (e) => { document.getElementById(‘coord’).innerHTML = x:${e.clientX} y:${e.clientY} });

Code snippet: HTML/JS Code for absolute mouse position in iframe

Regards, Nisha

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement