JQuery - disappear when you click on the parent element (and not on the parents)?

I have the following code on my page, and what I'm trying to do is that when the user clicks outside the #loginBox, I want the whole #loginOverlay to disappear. But I can’t achieve this effect without causing attenuation by clicking on #loginBox ...

It is placed at the bottom of the page, and I have a link on the page that launches fadein. But fadeout is fighting a bit now tbh.

I tried to do this:

$("#loginOverlay").click(function() { ...fadeout... });

but he gives me the same result.

So any suggestions? Thanks in advance!

<div id="loginOverlay">
    <div id="loginBox">
        <img class="closeBtn" src="images/icons/close.png" alt="" />
        <h3>Login</h3>
        <form action="login.php?ref=index.php" method="post">
            <input type="text" name="username" value="Username..." onblur="if(this.value.length == 0) this.value='Username...';" onclick="if(this.value == 'Username...') this.value='';" />
            <input type="password" name="password" value="Password..." onblur="if(this.value.length == 0) this.value='Password...';" onclick="if(this.value == 'Password...') this.value='';" />
            <input class="loginBtn" type="submit" name="submit" value="Login!" />
        </form>
    </div> <!--login box -->
</div>



<script src="js/jquery-1.4.2.min.js"></script>
<script>
$(document).ready(function() {
    $('#loginOverlay').css('display', 'none');

    $('#loginToggle').click(function() {
        $("#loginOverlay").fadeIn(200);
    });

    $("#loginBox").parent().click(function(){
        $("#loginOverlay").fadeOut(100);
    });

});
+3
source share
1 answer

e.target, , :

$("#loginOverlay").click(function(e) {
    if (e.target === this)
        $("#loginOverlay").fadeOut(100);
});
+6

Source: https://habr.com/ru/post/1743987/


All Articles