kamal
kamal

Reputation: 237

hide element when clicked anywhere on the page and show it by click on other element

I have an input text which i used for quick search, under this input there is a div which i use to show search result. by typing in input, the result is showing up in div.now i want to hide this element (meaning div) whenever i click on window and show it again by click on the input.I tried few jquery code to hide the element but i could not show it again.

$(window).click(function () {
    $('#livesearch').hide();
});
$('#search').click(function () {
    $('#livesearch').show();
});

Upvotes: 0

Views: 810

Answers (2)

wassim
wassim

Reputation: 69

I am not sure a click event exists for the "window" object. But I am no expert in JS for that matter.

Please check this code, I think it does what you want to achieve in a bit different way.


Edit: Please check this code. This prevents the search results from hiding if you click them. Since I am already studying JQuery I took the time to experiment with this, achieving this functionality feels more complex than it should be :)

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $(':not(.search_result)').focus(function () {
            $('#livesearch').hide();
        });
        $('#search').focus(function () {
            $('#livesearch').show();
        });
    });
</script>
</head>
<body>
<div>
    <input id='search' type="text" />
    <div id='livesearch' style='display: none'>
        <ul>
            <li><a class='search_result' href='#'>result#1</a></li>
            <li><a class='search_result' href='#'>result#2</a></li>
        </ul>
    </div>
</div>
<div>
    The rest of the page.
</div>
</body>
</html>

Upvotes: 1

steveyang
steveyang

Reputation: 9298

You should use the blur() and focus() event trigger of jQuery. doc

$('#input_window').blur(function () {
  $('#livesearch').hide();
}).focus(function () {
  $('#livesearch').show();
});

Change the #input_window to whatever in your html code.

Upvotes: 2

Related Questions