Ethan Bristow Ethan Bristow - 3 years ago 64
HTML Question

ToggleFade an element with display:none?

I'm trying to toggleFade a login box when a 'login' button is pressed. Until the 'login' button is pressed I want the box to be hidden with display:none so that it can't be seen or interacted with (I wasn't sure if having no visibility will prevent it's buttons from being clicked - maybe pointer events could be altered though).

The toggle works perfectly fine except for the first time the button is pressed in which the hide class is removed (displaying the box) but then the toggle fades OUT the box.

HTML:

<a id="loginBtn" class="loginBtn" href="/">Login</a>
<div id="loginContainer" class="loginContainer hide">
<a class="registerBtn" href="/">Register</a>
</div>


CSS:

.loginBtn {
color: #1493d1;
background: #fff;
border-radius: 98px;
cursor: pointer;
margin: 15px 0 0 0;
padding: 8px 15px;
position: absolute;
right: 0px;
/*float: right;*/
text-decoration: none;
}

.loginContainer {
width: 175px;
height: 250px;
background: #fff;
border-radius: 10px;
position: absolute;
top: 80px;
right: 0px;
/*float: right;*/
}

.hide {
display: none !important;
}


JS:

$(document).ready(function () {

var loginBtn = document.getElementById("loginBtn");

//DISPLAY MOBILE NAVIGATION ON HAMBURGER CLICK
function displayLogin() {
$('#loginContainer').removeClass("hide");
$('#loginContainer').fadeToggle("fast");
}

//EVENT LISTENERS
loginBtn.addEventListener("click", displayLogin);

}); //Doc Ready

Answer Source

Please find below mentioned solution.

$(document).ready(function () {

    var loginBtn = document.getElementById("loginBtn");

    //DISPLAY MOBILE NAVIGATION ON HAMBURGER CLICK
    function displayLogin(e) {
        e.preventDefault();
        $('#loginContainer').fadeToggle("fast");
        $('#loginContainer').removeClass("hide");
    }

    //EVENT LISTENERS
    loginBtn.addEventListener("click", displayLogin);

});
.loginBtn {
    color: #1493d1;
    background: #fff;
    border-radius: 98px;
    cursor: pointer;
    margin: 15px 0 0 0;
    padding: 8px 15px;
    position: absolute;
    right: 0px;
    /*float: right;*/
    text-decoration: none;
}

.loginContainer {
    width: 175px;
    height: 250px;
    background: #fff;
    border-radius: 10px;
    position: absolute;
    top: 80px;
    right: 0px;
    /*float: right;*/
}

.hide {
    display: none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="loginBtn" class="loginBtn" href="/">Login</a>
<div id="loginContainer" class="loginContainer hide">
    <a class="registerBtn" href="/">Register</a>
</div>

Let me know if it not works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download