view raw
LZERO LZERO - 7 months ago 31
HTML Question

Code for a left side menu opened by toggle

I'm currently doing a site where I want a toggle/icon to open the menu which slides in from the left on desktop view, then in mobile I just want it to drop down from the top and be responsive. Does anyone know how to do this?



This could be done in multiple ways, I would recommend using CSS:

CSS (Mobile First Approach):

// mobile
.menu {
  position: fixed;
  top: 0;
  height: 2em;

// desktop
@media (min-width: <desktop size>px){
  .menu {
    width: 2em;
    height: fit-content;

    /* smooth transition */
    will-change: transform;
    transition: transform 450ms linear;

    /* this centers the menu vertically and
    puts the menu out of the viewport. */
    top: 50%;
    left: 0;
    transform: translateY(-50%) translateX(-100%);
  } {
    /* this will put the menu in the viewport */
    transform: translateY(-50%) translateX(0);


var toggleButton = document.querySelector("#toggle-button");
var menu = document.querySelector("#menu");

toggleButton.addEventListener("click", function(){
}, false);

You might want to add prefixes and test across multiple devices.

That said, this problem is a little more complex than what I'm showing here. E.g. position fixed is a property that old browsers might have an issue with.