views:

77

answers:

3

I am trying to setup a fairly simple (imo) Javascript GUI, and am running into issues. I'm using jQuery. Here's what I want to do:

Have a bunch of squares next to some text, like this:

[ ] Text next to square
[ ] Text next to square 2
[ ] Text next to square 3
[ ] Text next to square 4

When you click one of the squares, an absolutely positioned floating div shows up. That floating div has some interface options.

At this point, if the user clicks anywhere OUTSIDE the floating div, the div should disappear. If the user clicks another box, the original div should disappear, and a new one should appear.

I am able to get the floating divs to show up correctly, but I'm having trouble hiding them. What I'm currently doing is attached a click handler to $(document) in the function that show the floating div. Simplified code is below:

show(jqueryObj)
{
    jqueryObj.show();
    $(document).one("click", function () { jqueryObj.hide(); });
}

(Show is bound to a lick on one of the [ ] boxes elsewhere)

The problem I run into is that the click event seems to bubble up, and function () { jqueryObj.hide(); } is executed immediately. I've tried returning false in show(), but that didn't seem to resolve the issue. What should I be doing here?

+1  A: 
$(document).click(function(e) {
    e.stopPropagation();
    var el = $(e.target);
    alert( el.get(0).nodeName );
});

Off the top of my head, are you looking for something like this? I ignored your code because it isn't standard jQuery and a bit abstracted.

meder
A: 

It could be that your click handler is getting called for the same click that it's added in. If that's the case then you would fix it by stopping the original click from bubbling (e.g. whatever is calling your function show).

Another option is to hack it:

show(jqueryObj)
{
    jqueryObj.show();
    setTimeout(function() {
        $(document).one("click", function () { jqueryObj.hide(); });
    }, 0);
}
Ken Browning
A: 

If I'm getting you right, your floating div disappears when you interact with it because that document click catches the interaction and hides it. If thats the case you need to check the target of your event and exit out if it is the floating div. Something like this:

$(document).click(function(e) {
    var target = $(e.target);
    if (target.is("#floatingDiv")) return;
    jqueryObj.hide();
});

Hope that helps

Edit: one thing to note is that you can check multiple conditions in the .is() call. So for example you could check for clicks on the floating div AND on one of your activation boxes:

if (target.is("#floatingDiv, .activateBox")) return;
Darko Z