MarkTwain MarkTwain - 1 month ago 7
HTML Question

Is there a way to shrink the callback of my menu button?

I'm quite new to Javascript and I'm trying to get my code more optimized.

So this is just a simple menu toggle I made and I'm wondering if there is a way to better optimize it because I kind of have almost to identical functions for handling the menu.



jQuery(function($) {
$(".open-menu").click(function(event){
event.preventDefault();
$('.menu').addClass('active');
} );

$(".close-menu").click(function(event){
event.preventDefault();
$('.menu').removeClass('active');
} );
});

.menu {
position: absolute;
left: 0;
top: 0;
width: 100%;
background: #f4f7fc;
margin-left: -100%;
transition: margin-left .5s ease;
}

.active {
margin-left: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="menu">
<ul>
<li><a href="#close-menu" class="close-menu">Close</a></li>
<li><a href="#">Home</a></li>
<li><a href="#about">About our project</li></a>
</ul>
</div>

<a href="#open-menu" class="open-menu">Open menu</a>




Answer Source

Welcome to StackOverflow. There are a few ways to optimize your code.

  1. You have a small error in your HTML: <li><a href="#about">About our project</li></a>. Your closing </a></li> is swapped.
  2. You could use a styled button instead of an anchor, so you'd be able to shrink your code even further.
  3. You could change your opening and closing links to one generic class and then use toggleClass
  4. For better performance, instead of using margin-left use transform: translateX (here is an article about why)

jQuery( function( $ ) {
  $( '.menu-toggle' )
    .click( () => $( '.menu' ).toggleClass( 'active' ) );
} );
.menu {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  background: #f4f7fc;
  transform: translateX( -100% );
  transition: transform .5s ease;
}

.active {
  transform: translateX( 0 );
}

.menu-toggle {
  background: none;
  border: none;
  padding: inherit;
  margin: inherit;
  font: inherit;
  
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="menu">
  <ul>
    <li><button class="menu-toggle">Close</button></li>
    <li><a href="#">Home</a></li>
    <li><a href="#about">About our project</a></li>
  </ul>
</div>

<button class="menu-toggle">Open menu</button>