Skip to content Skip to sidebar Skip to footer

Jquery - Click Outside And Hide Div

I am using this: http://www.useful-dates.com/search/ How should the script be written to say, 1. When the user clicks the input, the scrolled div is shown. 2. When the user click

Solution 1:

The easiest way of doing this is when your script is triggered to display the list (the scrolled div) it creates a trigger to the click event on the document itself aswell. Something like this:

$("selector to your div").click(function() {
    var scrolledDiv = $("selector to your scrolled div");
    scrolledDiv.show();
    $(document).one(function() {
        scrolledDiv.hide();
    });
});

By using the one() the code to hide the scroll list will only be executed once, so it wont run each time the user is clicking the document. But remember that it will also trigger on clicks inside your scrolling div, if you dont want that stop the propagation of the click event like this:

$("selector to your scrolled div").click(function(e) {
    e.stopPropagation();
});

Solution 2:

If you look at the source code of your example ;

            $(document).click(function(){

                $('.ddcontainer > div > ol').hide();

            });

This hides the div when there has been a click on the document.

Give you div an ID like so:

<div id="searchResults" style="height:95px;width:290px;overflow:scroll;overflow-x:hidden;margin: 2px 0 0 0;">

and then:

$(document).click(function(){

    $('#searchResults').hide();

});

Alternatively and maybe a better solution is to use focus and blur:

$("#kwd_search").focus(function(){
    $('#searchResults').show();
}).blur(function(){
    $('#searchResults').hide();
});

This will show the results when the focus is put onto the input, and removes it when you 'leave' the input.

UPDATE

With the autocomplete plugin, you can perform a task after the item has been selected like this:

$( "#tags" ).autocomplete({
    source: availableTags
}).bind( "autocompleteselect", function(event, ui) {
    location.href = ui.item.value; // If the value of the item is a url, this will forward you to it
});

Post a Comment for "Jquery - Click Outside And Hide Div"