Coding a hamburger menu with JS, CSS & HTML

Posted on

Problem

I’ve created a menu that allows you to display the list when clicking on the menu icon. I wonder whether this can be improved somehow – can anyone help improve this?

Also, initially I created it with the event passed into the script to prevent it from scrolling to the top when clicking on the link. I then changed it to an ES6 function – does it not need the event passed in and calling e.preventDefault()?

Thank you. The code is as follows:

  const cont = document.querySelector('.cont');
  const hamburger = document.querySelector('#hamburger');
  
  // const toggleMenu = (e) => {
  //   e.preventDefault();
  //   cont.classList.toggle('open');
  // }
  const toggleDisplay = () => cont.classList.toggle('open');
  
  hamburger.addEventListener('click', toggleDisplay);
.cont {
  position: relative;
}
a {
  font-size: 3em;
}
a:hover {
  cursor: pointer;
}
a::after {
  content: '02b';
}
.open a::after {
  content: '0d7';
  color: red;
}
.open ul {
  display: flex;
}
ul {
  all: unset;
  display: none;
  position: absolute;
  background: #0ff;
  padding: .5em;
  min-width: 100px;
  top: 100%;
  left: 0;
  flex-direction: column;
  text-align: center;
}
li {
  all: unset;
  width: 100%;
}
li:not(:first-child) {
  margin-top: .5em;
  padding-top: .5em;
  border-top: 1px solid #ccc;
}
<div class='cont'>
  <a id='hamburger'></a>
  <ul>
    <li>First</li>
    <li>Second</li>
    <li>Third</li>
  </ul>
</div>

Solution

Here are a few suggestions:

  • ‘.cont’ is a bit vague – I suppose it means container but try to avoid meaningless abbreviations
  • Be careful with all: unset. It might have unexpected consequences cross-browser.
  • I would stick to rem for margin/paddings and only use em for fontsizes. There is a lot of articles explaining the difference if you perform a simple google search
  • You could make it behave a little more smoothly if you had a CSS transition
  • Instead of a wrapping div this could potentially be a nav element if it is part of some navigation. Always try to use semantically correct tags
  • I don’t think you want an a tag here as you are not linking to anything. Maybe a button would be better?

As for your question both of your functions are ES6 functions (fat-arrow functions).

In the example you commented out you are using explicit return while you are using implicit return in the latter.

Leave a Reply

Your email address will not be published. Required fields are marked *