开发者

auto-complete search suggestion drop-down popup

Im trying to make a popup div (when a text-box value changes) and it can be closed (visibility: none) by clicking anywhere outside the div. Similar to Google 开发者_如何学Gosuggestion drop-down.

How can I know weather the mouse click has happened inside the div or outside.

I need to implement this using javascript and jsp.

Please help.


The jquery solution would be

$("body > div").click(function() {
if ($(this).attr("id") == "div-id") {
    // inside the DIV
} else {
    // not inside the DIV
}
});

or

$("html").click(function (e)
{
if (e.target == document.getElementById("div-id"))
    alert("Inside DIV");
else
    alert("Outside DIV!");
});

or Javascript snippet would be something like this:

<script type="text/javascript"> 
document.onclick=check; 
function check(e){ 
var target = (e && e.target) || (event && event.srcElement); 
var obj = document.getElementById('div-id'); 
if(target!=obj){obj.style.display='none'} 
} 
</script>


One method would be to popup a div behind that covers the whole screen (invisible), and capture clicks on that div to close both popup divs. You could also try capturing clicks on the body tag and that should catch clicks anywhere outside the div (or inside the div as well if events bubble - you may want to perform some testing).

Sometimes an easier method is to use a timeout, like popup CSS menus that disappear once your mouse has been off of the menu for a couple of seconds. You can catch the onmouseleave event, start a timer, and as long as there isn't another onmouseenter in say, two seconds, then hide the popup div.

Hope this helps!


Here's an example with jQuery. If you click on the "test" text, you make the other text appear. Clicking anywhere else except than on the newly appeared text makes it disappear.

This works because if the click happened inside (the .toggle object, in this case), we call e.stopPropagation() for the click event to stop propagating further up towards the entire window. However if the click occurred somewhere else, it propagates directly to the window and makes .toggle disappear.

See example of it working on jsfiddle.

<script src="js/jquery-1.4.4.min.js"></script>
<script>
    $(function(){
        $('.test').bind('click', function(e){ 
            $('.toggle').fadeIn(); 
            e.stopPropagation();
        });
        $('.toggle').bind('click', function(e){ 
            e.stopPropagation(); 
        });
        $(document).bind('click', function(){ 
            $('.toggle').fadeOut(); 
        });
    });
</script>

<a class="test" href="#">test</a>
<div class="toggle">asdasdsa</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜