0

I'm detecting if the mouse leaves the window as specified in this answer: How can I detect when the mouse leaves the window?.

The problem is that the browser triggers this event when the mouse enters an iframe (an embedded Youtube video in my case).

How can I prevent that?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sami
  • 648
  • 8
  • 25
  • Hmmm, I don't think you can directly you will have to apply some sort of hack or workaround. By definition an iframe is a different window... let me think on this. – Ryan Dec 11 '12 at 01:33

1 Answers1

1

You simply have to modify the handler this way:

addEvent(document, "mouseout", function(e) {
    e = e ? e : window.event;
    var from = e.relatedTarget || e.toElement;

    // we will check if this won't be iframe
    var to = e.target || e.srcElement;
    if ((!from || from.nodeName == "HTML")
      && to.nodeName !== "IFRAME") {
        console.log('mouse out')
    }
});

EDIT Added e.srcElement option to support IE

Bogdan Kulynych
  • 683
  • 1
  • 6
  • 17
  • Do you know if this solution is cross-browser? – Sami Dec 11 '12 at 08:13
  • This works mostly (in Firefox at least). But there still seems to be some false positive when the mouse goes fast over the iframe and back in the document. – Sami Dec 11 '12 at 09:19
  • I can't test it right now, but I am quite sure that `e.srcElement` will be IE compatible. I've edited the post. And with fast mouse move, it doesn't trigger anything for me, how did you do that? – Bogdan Kulynych Dec 11 '12 at 10:24
  • I'm not sure exactly why it does that, I have two iframes embeded (one in each other, the youtube video is in the second one). When the event is triggered the `from` var is `undefined` and the `to` var points to the background image of the body. But it's not really important since it is triggered really rarely. – Sami Dec 11 '12 at 16:16