简体   繁体   中英

Exit Div Only On Click Of Background With Javascript(Jquery) [For Popup]

I am in a bit of a predicament. I have a popup currently, and I would like the popup to close when either the background is clicked, or the "ex out" button is clicked. Problem is, it will close the popup when the main box is clicked. Here is my HTML:

<div id="newcommentcontainer">
    <div id="newcommentholder" class="col-xs-12 col-sm-8 col-sm-offset-2 col-lg-6 col-lg-offset-3">
        <form method="post" class="col-xs-12">
            <div id="exoutnewcommentholder" class="col-xs-12">
                <span class="glyphicon glyphicon-remove" id="exoutnewcomment"></span>
            </div>
            <div id="newcommenttitle" class="col-xs-12"> Add New Comment </div>
            <textarea id="commentinput" name="commentinput" class="col-xs-12 col-sm-8 col-sm-offset-2" placeholder="Type your Comment here."></textarea>
            <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-lg-6 col-lg-offset-3">
                <button id="createcommentbutton" class="col-xs-12" input type="submit" value="addcomment">Add Comment</button>
            </div>
            <div id="commentcharactercount" class="col-xs-12"> 0 / 500 Characters. </div>
            <input type="text" id="commentlengthholder" name="commentlengthholder" style="display:none">
        </form>
    </div>
</div>

So basically, when #newcommentcontainer (First Div), is clicked on, the whole thing closes. If #newcommentholder is clicked, nothing happens, because that is what holds the information. Yet, if #exoutnewcommentholder is click, the whole thing closes as well.

Simply, I would like the whole thing to display: none when it is clicked EXCEPT if it is clicked within the #newcommentholder (excluding ex out button).

I have started with this JQuery:

    $("#newcommentcontainer").click(function(e) {
        $("#newcommentcontainer").css("display","none");
    });

But I am not sure on how to continue from here. Please help! :)

You can use 2 click handlers, the second one will prevent the propagation of click event from newcommentholder so that clicks inside that will not close the popup

$("#newcommentcontainer, #exoutnewcommentholder").click(function (e) {
    $("#newcommentcontainer").hide();
});
$('#newcommentholder').click(function (e) {
    //stop propagation to newcommentcontainer element
    e.stopPropagation();
})

Another option you can try is(not tested) to check the target element is within newcommentholder like

$("#newcommentcontainer").click(function (e) {
    var $target = $(e.target);
    if ($target.closest('#exoutnewcommentholder').length || !$target.closest('#newcommentholder').length) {
        $("#newcommentcontainer").hide();
    }
});

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