Diana
Diana

Reputation: 435

Detect click outside an element (with frames)

I have a main page (main.html) which opens an iframe page (iframe.html).. The iframe is appended as a kind of thickbox window on main.html .Now on this iframe.html, there is a div element "myDiv" and I need to detect click outside of this myDiv element..

The script is written inside a JS called in iframe.html

I already tried a few things (binding event to document and removing from myDiv), but that is not working..

$(document).click(function() {
  //your code here
});

$("#myDiv").unbind("click");

I am not sure if this issue has got anything to do because of the iframe...

Please help me. Thank you.

Upvotes: 2

Views: 2963

Answers (3)

exoboy
exoboy

Reputation: 2058

Have you tried something like this? It listens for all clicks on the document, but only triggers your code if the target of the event is not the myDiv element. This way, you can tell if the click was outside the myDiv element or not.... I used jQuery:

// assign a document listener $(document).click(function(e){

if( $(e.target).attr('id') != "myDiv" )
{
  // execute your code here
  alert( e.target );        }
});

// assign an element listener
$('#myDiv').live('click',function(){alert("clicked on myDiv")});

It also allows you to assign specific code to the myDiv element to be executed if the user clicks on the myDiv element directly...

Upvotes: 1

Mikhail
Mikhail

Reputation: 9007

This is a "flag & ignore" routine that I was talking about. I'm hoping there's a jQuery-native method to do this, because using flags like this is a dirty hack IMO

var myDiv = false;
$(document).click(function() {
  if (!myDiv) {
    // your code here
  }
  myDiv = false;
});

$("#myDiv").click(function(e){
  myDiv = true;
  return false; // don't know if returning false will stop propagation in jQuery
});

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69915

I think you want to hide the myDiv if you click outside of it, try this.

$(document).click(function() {
  $("#myDiv").hide();
});

$("#myDiv").click(function(e){
  e.stopPropagation();
});

Upvotes: 0

Related Questions