Search code examples
javascriptiframeeditorwysiwyg

Find the element the user clicked inside an iframe


I am working on a HTML Editor using an iframe, I want users to be able to resize images once added. so when the user clicks on an image inside the iframe have a listener running. But all it gives me is the body tag rather than the element clicked. I have tried this many ways but none seem to work.

My code for this area is:

//site display is the iframe

//iframeBody is theid of bodyinside iframe

siteDisplay.document.getElementById('iframeBody').addEventListener("click", testForClicks, false); 


function testForClicks(){

 console.log(siteDisplay.document.activeElement);

 console.log(this);

 //both give me bodytag

}

I need to get the element clicked or the element highlighted

Any help would be great, Thanks


Solution

  • If you need the highlighted (or active) element you can use the Selection/Range (link) API

    var selection = window.getSelection();
    var range = selection.getRangeAt(0);
    var firstNode = range.startContainer;
    // etc.