1

I have a DIV element that appears when a certain action is performed. For the sake of simplicity, I wrote a very simple routine that mimics the issue I'm running into. The problem I am facing, however, is that when you click inside the DIV element (and outside the textarea), it will hide the DIV anyway.

Here is the code below:

<body>
outside div
<br><br>

<a href="#" id="wrap_on">make inside appear</a>
<br><br>

<div id='wrap' style='background:red;display:none;padding:10px;width:155px'>
    <textarea id='inside'>inside div</textarea>
    <div id='inside2'>also inside div -- click me</div>
</div>
</body>

<script>
$(document).ready(function() {
    $('#wrap_on').click(function() {
        $('#wrap').show();
        $('#inside').select().focus();    
    });

    $('#inside2').click(function() {
        alert('test');
    });

    // #inside2 does not work but #wrap does hide
    $('#wrap').focusout(function() {
        $('#wrap').hide();
    });
});
</script>

Or you can tinker with it here: http://jsfiddle.net/hQjCc/

Basically, I want to be able to click on the text "also inside div -- click me" and have the alert popup. However, the .focusout function is preventing it from working. Also, I want to hide the #wrap DIV if you click outside of it.

James Nine
  • 2,548
  • 10
  • 36
  • 53

2 Answers2

2
$(document).click(function(e) {
    var t = (e.target)
        if(t!= $("#inside").get(0) && t!=$("#inside2").get(0) && t!=$("#wrap_on").get(0) ) {
            $("#wrap").hide();
        }
});

this should work after all.

http://jsfiddle.net/hQjCc/4/

Gergely Fehérvári
  • 7,811
  • 6
  • 47
  • 74
0

See this other stack overflow question: Use jQuery to hide a DIV when the user clicks outside of it

Community
  • 1
  • 1
JK.
  • 21,477
  • 35
  • 135
  • 214
  • That also doesn't work. Clicking outside the DIV doesn't hide it at all, but the alert does show. http://jsfiddle.net/hQjCc/2/ – James Nine Feb 06 '11 at 10:21