0

I searched among the various solutions but none seem to work. For that I return here to find concomitantly with you a solution. I created this sort of window to share and customize the things of my site. The problem is that when i want to close i want click out of div (black zone). Sorry for the English but I'm Italian.

`http://jsfiddle.net/34uLs/`
John Dvorak
  • 26,799
  • 13
  • 69
  • 83

2 Answers2

1

This question is indeed a duplicate of hide div if clicked outside of it

However in this scenario, since the dark background #shead is the top most element, the click event should be attached to it. If the click event is attached to the $(document) object it will never reach it because #shead will capture it.

Solution:

jsFiddle

/** The event should be binded with this element **/
$('#shead').click(function () {
    $(this).toggleClass("open");
});

Further Readings

Community
  • 1
  • 1
Bassem
  • 3,135
  • 2
  • 25
  • 41
1

One possible solution is that which was recommended by Ankit (he seems to have deleted his post). Here is a jsfiddle example of it in action: http://jsfiddle.net/drb9w/11/. This does have the weakness, however, of the browser styles for focused objects being applied to the #share element.

$('#moresh').click(function (event) {
    var elt = $(this).attr('for');
    $("#" + elt).toggleClass("open");
    $("#share").focus();
});
$(function () {
    $("#share").draggable();
});
$("#share").on('blur', function(event) {
    $('#shead').removeClass("open");
});

How it works:

  1. Focus the #share element so that it can be blurred (unfocused).
  2. When the #share element is blurred, remove the open class.

If you want to maintain the functionality of your 'for' attribute, use the data argument of the on function.

There is an alternative method which avoids the problem of the focus decorators being applied to #share: register a click listener to the parent element (which seems to cover the entire screen) which is prevented from activating by the #share element like so:

$('#moresh').on('click', function(event) {
    var elt = $(this).attr('for');
    $("#" + elt).toggleClass("open");

    function onBodyClick(event) {
        $(this).off('click', '', onBodyClick);
        $(this).removeClass('open');
    }

    $("#" + elt).on('click', onBodyClick);
});
$(function() {
    $("#share").draggable();
});
$("#share").on('click', function(event) {
    event.stopPropagation();
});

http://jsfiddle.net/trG2n/6/

J David Smith
  • 4,780
  • 1
  • 19
  • 24
  • Thanks for your help but BassemDy responded before. I must admit that both solutions are perfect for what I need but the above seems like a less demanding. – Selena Golieador Jun 27 '13 at 17:32