senojoeht senojoeht - 4 months ago 19
Javascript Question

Using CSS animations to slide a menu on click event

I'm attempting to create a menu that slides out on a click event, then slides back in when that element is clicked again.

Here is a codepen of what I have.
http://codepen.io/anon/pen/wWpjWa

and the js which is the problem:

$('#menu-link').click(function(){
$('#menu-link').toggleClass('slideIn');
$('nav').toggleClass('slideIn');
$('#menu-link').toggleClass('slideOut');
$('nav').toggleClass('slideOut');
});


Naturally both animations are launched at once.

I know the problem here is that it's toggling both the slideIn and slideOut classes at the same time. A solution could be to add the slideOut class to the elements. But this will launch the animation once before any events.
I've gone through various solutions which don't quite work. I know it's simple I just can't think how to solve it.

Answer

You need to check whether it's already out or not by checking the class on it ( use hasClass() ).

$('#menu-link').click(function(){
  if( $("#menu-link").hasClass("slideIn") )
    {
      $('#menu-link').toggleClass('slideOut');
      $('nav').toggleClass('slideOut');  
    }
    else
    {
      $('#menu-link').toggleClass('slideIn');
      $('nav').toggleClass('slideIn');    
    }  
});
body {
  font-family: 'Roboto', 'Helvetica', sans-serif;
}

h1 {
  font-size: 3rem;
  font-weight: 700;
}

.wrapper {
  padding: 4rem;
  width: 70%;
  height: 100%;
  margin: 0 auto;
}

nav {
  height: 100%;
  background: #3385ff;
  width: 300px;
  position: fixed;
  left: -300px;
  border: none;
}

a,
a:hover,
a:visited {
  color: white;
  text-decoration: none;
}

ul {
  width: 50%;
  margin: 0 auto;
  list-style: none;
  font-size: 1.7rem;
}

li {
  text-align: center;
  padding-top: 70%;
}

#menu-link {
  position: absolute;
  color: #3385ff;
  padding: 10px;
  font-size: 4rem;
}


/*ANIMATIONS*/

.slideIn {
  animation: menuSlide .5s 1;
  animation-fill-mode: forwards;
}

.slideOut {
  animation: menuSlideOut .5s 1;
}

/*Keyframes*/

@keyframes menuSlide {
  from {
    transform: translateX(0px);
    transition-timing-function: ease-in;
  }
  to {
    transform: translateX(300px);
    transition-timing-function: ease-out;
  }
}

@keyframes menuSlideOut {
  from {
    transform: translateX(300px);
    transition-timing-function: ease-in;
  }
  to {
    transform: translateX(0px);
    transition-timing-function: ease-out;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<header>
  <nav role="navigation">

  </nav>
  <a href="#" id="menu-link">&#9776;</a>
</header>

<main>
</main>

Comments