Search code examples
javascriptjquerydomweb-frontend

Clickoutside event doen't work on iframe


It's a rich-text editor,there is a div show the content users typed in, just like this:

<div class=‘content’>
    <iframe data-role=text-editable.></iframe>
</div>

When i click a icon who's used to call the color panel,the panel will show.And i wish when i click outside the panel,it will be hide.so my code is:

var  color_panel = $('.color-panel');
     color_panel.on("clickoutside",        function (e) {                   
    var t = $(e.target);            
    if ($.contains(color_panel[0], t[0]))                  
        return;   
    color_panel.hide();
})

It works well when i click outside the panel will disappear except i click the iframe.when i click the ifame,nothing happens,the panel is still shown,

Help......i want to know the reason .please...is the ifame not the dom element outside the panel?


Solution

  • You can listen for outside clicks by listening for clicks on the body element of the webpage (so, clicking on anything element) and then you can exclude your .color_panel from this event by making another event that says "when I get clicked on, ignore any other clicks". The effect will be exactly what you want, that you can listen for outside clicks:

    var panelOpen = false;
    
    $('body').click(function(event) {
      if (panelOpen) {
        panelOpen = false;
        color_panel.hide();
      }
    });
    
    $('.color_panel').click(function(event) {
      panelOpen = true;
      //callYourMethodToShowThePanelHere();
      e.preventDefault(); // these methods will stop the body click event
      e.stopPropagation();
      return false;
    });