markite markite - 3 months ago 12
CSS Question

toggleClass works only at first click (IE, FF)

This is my very first question and I'm rarely ask for help before I find the answer myself but this one got me for real.

I have the following:

HTML

<!-- This one opens/shows the nav. I should change div to a button tag -->
<div class="menu"><a id="menu-open" class="menu-open" href="#">&#9776;</a></div>
<nav id="navigation" class="navigation">
<!-- This on closes/hide the nav -->
<button type="button" value="Close" class="button-close">
<a id="menu-close" class="menu-close">X</a>
</button>
<h1>User Name</h1>
<p class="mail"><sec:authentication property="principal.username" /></p>
</nav>


CSS

.navigation {
position: fixed;
background: #fff;
width: 100%;
height: 100vh;
top: 0;
z-index: -100;
display: none;
text-align: center;
font-weight: bold;
}

.navigation-open {
z-index: 100;
display: inherit;
}


jQuery

$(document).ready(function(){

$(".menu-open").click(function(){
$(".navigation").toggleClass("navigation-open")
});
$(".menu-close").click(function(){
$(".navigation").toggleClass("navigation-open")
});
});


When I hit the a tag with menu-open class it actually shows the nav tag (meaning, I guess, toggleClass is working), but then just after that I hit a tag with menu-close class and no toggling is execute.

This issue happens on IE and FF but not CH

I'm using CH 52, IE 11 and FF 46.

I've already tried:


  • Changing jQuery version from 1.x to 3.x

  • Using e.stopPropagation() function and redirecting the handling to html



I'd appreciate any help on this one since it's driving me nuts.

Thanks in advance!

Answer

Button elements shouldn't have an anchor inside them.

Check this:

$(document).ready(function(){

    $(".menu-open").click(function(){
       $(".navigation").toggleClass("navigation-open")                  
    });
    $(".menu-close").click(function(){
       $(".navigation").toggleClass("navigation-open")
    });
});
.navigation {
        position: fixed;
        background: #fff;
        width: 100%;
        height: 100vh;
        top: 0;
        z-index: -100;
        display: none;
        text-align: center;
        font-weight: bold;
}

.navigation-open {
        z-index: 100;
        display: inherit;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- This one opens/shows the nav. I should change div to a button tag -->
<div class="menu"><a id="menu-open" class="menu-open" href="#">&#9776;</a></div>
<nav id="navigation" class="navigation">
    <!-- This on closes/hide the nav --> 
    <button type="button" value="Close" class="button-close menu-close">
        X
    </button>
    <h1>User Name</h1>
    <p class="mail"><sec:authentication property="principal.username" /></p>
</nav>