Johan Hjalmarsson Johan Hjalmarsson - 5 months ago 10
CSS Question

.on('click') works, .css('display','block') works, but not together

I'm having a strange problem. I've got this:

<div id="tstbtn" style="width:10px; height:10px; background-color:green;"></div>
<div id="dvDRKN">
<div id="dvPopup">
<asp:DropDownList ID="ddlDDL" runat="server">
<asp:ListItem Text="Test" />
</asp:DropDownList>
</div>
</div>

<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', function (event) {
if (!$(event.target).closest('#dvPopup').length) {
$('#dvDRKN').css('display', 'none');
}
});

$('#tstbtn').on('click', function () {
$('#dvDRKN').css('display', 'block');
});
});
</script>

<style type="text/css">
#dvDRKN
{
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.6);
position: fixed;
display:none;
}
#dvPopup
{
position: fixed;
padding: 20px 15px;
background-color: white;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
}
</style>


It's supposed to show the
#dvDRKN
div when I click the
#tstbtn
div, but it doesn't.

I've tested the following:

$('#tstbtn').on('click', function () {
alert('test');
});


And that worked fine.
I've also tested to input
$('#dvDRKN').css('display', 'block');
directly in the console, and that also works. But when I put the two together, nothing happens.

Answer

Add return false; to prevent it from bubbling to parent event which toggles the state of the div, which you don't want to happen.

  <script type="text/javascript">
        $(document).ready(function () {
            $(document).on('click', function (event) {
                if (!$(event.target).closest('#dvPopup').length) {
                    $('#dvDRKN').css('display', 'none');
                }
            });

            $('#tstbtn').on('click', function () {
                $('#dvDRKN').css('display', 'block');
                return false;
            });
        });
    </script>