简体   繁体   中英

Grouping elements for focus/onblur events?

I have an autocomplete div which appears when the user keyup's in a search field. I want the div to disappear when they click outside of the div, so I have tried the following:

//SHOW THE DIV WHEN INPUT CLICKED
$('#searchbar').focus(function(){
    $('#div').show();   
});

//HIDE THE DIV WHEN FOCUS LOST
$('#searchbar').on("blur", function(){
    $('#div').hide();   
});

Unfortunately, the div which houses the autocomplete choices contain tags that I want the user to click. As soon as the user clicks a link, the div disappears (because focus from the input field is lost).

So is there any way to 'group' the div with the input field so they can both be 'focussed' when the input is active, or div is clicked?

Regards, and thank you in advance!

EDIT: Here is my HTML

<div class="appBar">
    <table class="abTable">
        <tr>
            <td><b><a href="index.php"><span style="color:white;">gelDB</span></a></b></td>
            <td><input id="sbar" type="text" name="searchBar" class="searchBar" placeholder="Search for entries..." /></td>
            <td>
            <a href="entry.php"><img class="navButton" alt="" src="images/btn_new.png" style="width: 50px; height: 50px" /></a>
            <a href="browse.php"><img class="navButton" alt="" src="images/btn_browse.png" style="width: 50px; height: 50px" /></a>
            <a href="protocols.php"><img class="navButton" alt="" src="images/btn_proto.png" style="width: 50px; height: 50px" /></a>
            <img class="navButton" alt="" src="images/btn_permis.png" style="width: 50px; height: 50px" />
            </td>
            <td>
            <button class="menuButton"></button>
            </td>
        </tr>
        <div class="menuButtonDiv"></div>
    </table>
</div>
</head>
<br/>
<body>
<div id="acd" class="autoCompleteDiv">No results. Try searching something else.<hr></div>

Here is a graphical example of what I'm doing: 在此处输入图片说明

Figured it out, had to use the following code:

$('#sbar').on("blur", function(){
    if ($('#acd').is(':hover')) {}
    else{$('#acd').hide();};
});

Basically it states to hide the div unless the mouse is currently over (hovering over) the div.

try this:

<div id="box">
    <a href="#">link<a>
<div>

_

    $( "body" ).click(function() {
        // if the element that was clicked is #box OR any child of #box
        if($(event.target).is( "#box, #box > *" )) {

        } else {
            alert("outside the box");
        }
    });

demo: http://jsfiddle.net/J9yzj/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM