-1

I have a page with many iframe and I should open a drop-down menu on top of all them by append the menu at the top body.
Problem is that how can I catch the next click of the mouse to close the menu? Because I don't know in which frame it will be I can't add an click listener to the right iframe.
Is there any way to catch the click event instead of the click event on the target element?

jsFiddle example - if I click inside the iframe the menu will not be removed!

TheGr8_Nik
  • 3,080
  • 4
  • 18
  • 33

1 Answers1

1

You could use this kind of workaround which will work on any iframe (cross domain too). But would need more testing:

--DEMO--

$(focusWindow);

$('iframe').on('mouseenter', function () {
    $(window).on('blur', iframeclicked);
}).on('mouseleave', function () {
    $(window).off('blur', iframeclicked);
    if($(document.activeElement).is('iframe'))
        focusWindow();
});

function iframeclicked(){
     $("#myMenu").remove();
}

function focusWindow(){
    $('<div/>').attr('tabindex',-1).prependTo('body').focus().remove();
}

//$(window).mouseenter(focusWindow); << removed it
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • It seems to work, but I haven't understand the `focusWindow` function. – TheGr8_Nik May 20 '14 at 10:38
  • This is just a workaround for cross browser behaviour to set focus on window once DOM is ready. You could find better way and could for example handle case where e.g an input as autofocus set, etc... This would need more testing for sure. Indeed the idea is to check for window on blur event which is fired when an iframe (cross domain or not) is clicked. But as this event can be fired from multiple causes, we handle it to check if user is currently over an iframe on page or not, that's the idea behind it – A. Wolff May 20 '14 at 10:41
  • That's said, if all your iframes are from same domain, better would be to handle it from iframe code, targeting parent document function – A. Wolff May 20 '14 at 10:45
  • now I understand how it works! The frame have dynamic source and some times cross domain, so the proposed version is ok. I only changed the `appendTo('body')` with the `prependTo('body')` otherwise at opening of the menu the iframe scrolls down ;-) – TheGr8_Nik May 20 '14 at 12:20
  • @TheGr8_Nik Prepending element sounds better indeed, thx for the feedback :) – A. Wolff May 20 '14 at 13:53
  • Another improvement, in the `iframeclicked` function I have added the following line to unbind the `mouseenter` and `mouseleave` events: `$('iframe').off('mouseenter mouseleave');` – TheGr8_Nik May 21 '14 at 07:20