简体   繁体   中英

How to close an alert box when clicking on it?

Hey guys and girls. Made this custom alert box.

<script type="text/javascript">
    $(function () {
        var $alert = $('#alert');
        if ($alert.length) {
            var alerttimer = window.setTimeout(function () {
                $alert.trigger('click');
            });
            $alert.animate({ height: $alert.css('line-height') || '80px' }, 200).click(function () {
                window.clearTimeout(alerttimer);
                $alert.animate({ height: '0' }, 200);
            });
        }
    });
</script> 

I want it to be open until the user chooses to click on it or anywhere else on the screen. Who do I make this happen?

Thanx for your help!

Assuming that clicking anywhere (in, or out, of the alert box itself) is supposed to hide/remove the alert:

$('body').click(
    function(){
        if ($alert.is(':visible')){
            $alert.hide();
        }
    });

should work, I think.

If you want to justs get rid of it, try calling the hide() function when an onclick event is triggered.

$.click(function() {
  $alert.hide();
});

The top answer here is excellent IMO. It covers the part about anywhere else on the screen .

The way to do it is to bind a click event to the body and stop propagation on any event that happens inside the area that isn't supposed to trigger closing the alert.

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