Carl Edwards
Carl Edwards

Reputation: 14454

Adding/Removing a div overlay via click, button click, or escape key

I have a basic div overlay which functions when a user clicks inside an input box:

HTML

<html>
<body>
    <input id="search" type="text" placeholder="Search...">
</body>
</html>

CSS

#overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: #000;
    filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
    z-index: 10000;
    display: block;
}

JS

$(function() {
   var overlay = $('<div id="overlay"> </div>');
   $("#search").one('click', function(e) {
       overlay.appendTo(document.body)
   });
});

My overall goal is to have this div 'hide' by clicking outside the input box, pressing the escape button, or clicking a button that I plan to put to the right of the form. What would be the best approach to accomplish this from what I currently have?

Upvotes: 0

Views: 9648

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

Something like

jQuery(function ($) {
    $("#search").on('click', function (e) {
        if (!$('#overlay').length) {
            $('body').append('<div id="overlay"> </div>')
        }
    }).keyup(function (e) {
        if (e.which == 27) {
            $('#overlay').remove();
        }
    }).blur(function (e) {
        $('#overlay').remove();
    });
    $('body').click(function (e) {
        if (!$(e.target).is('#search')) {
            $('#overlay').remove();
        }
    })
});

Demo: Fiddle

Upvotes: 5

Related Questions