goo
goo

Reputation: 2280

How do you hide a div by clicking anywhere outside that div?

I'm displaying an iframe overlay with a z-index of 9999 with 100% width and height. The actual div inside the iframe is is only 620px wide. The problem is, I can not hide the iframe by simply click outside that div. Here's the code I'm using now

$(document).click(function() {
    alert("hide iframe");
});
$(".myDivInsideMyIframe").click(function(e) {
    e.stopPropagation();
    return false;      
});

How can I hide my iframe by click outside the div thats inside?


jsfiddle: http://jsfiddle.net/H5Vpd/7/


To make what I'm trying to do clearer:

The widget is coming from my domain and will be embedded on others. I can't control whats on other domain but I think it'd be nice if the user clicks outside the div thats in my iframe, it would hide the iframe

Upvotes: 1

Views: 708

Answers (4)

Gildas.Tambo
Gildas.Tambo

Reputation: 22663

you can use the all + not selector like this:

$("*:not(.div2hide)").click(function() {
  $(".div2hide").hide();     
});

Upvotes: 0

federicot
federicot

Reputation: 12341

You might be looking for this. This would only work if the src of the iframe points to a resource in the same domain, for security reasons.

$(document).mouseup(function (e)
{
    // Grab your div
    var foo = $('iframe').each(function() {
        return $('.myDivInsideMyIframe', this.contentWindow.document || this.contentDocument);
    });

    if (!foo.is(e.target) && foo.has(e.target).length === 0) {
        // If the target of the click isn't the div
        // nor a descendant of the div

        // Hide the iframe
        $('iframe').hide();
    }
});

Upvotes: 1

Graham Swan
Graham Swan

Reputation: 4838

I recommend using the jQuery Fancybox plugin to display overlays on your site. Not only will it handle all of the centering and click events for you, it also supports iframes out of the box.

$.fancybox({
  href: 'http://google.com/'
});

View its documentation here: http://fancyapps.com/fancybox/#docs

Upvotes: 0

Maciej Czekaj
Maciej Czekaj

Reputation: 64

maybe try:

$("iframe div:not(.myDivInsideMyIframe)").click(function() {
  $(iframe).hide();     
});

Upvotes: 0

Related Questions