What is the best way to conceal a menu that automatically scrolls to the content when it is clicked?

Below is a Codepen with a menu that isn't behaving as expected.

var menu = document.querySelector('.nav__list');
var burger = document.querySelector('.burger');
var doc = $(document);
var l = $('.scrolly');
var panel = $('.panel');
var vh = $(window).height();

var openMenu = function() {
  burger.classList.toggle('burger--active');
  menu.classList.toggle('nav__list--active');
};

// reveal content of first panel by default
panel.eq(0).find('.panel__content').addClass('panel__content--active');

var scrollFx = function() {
  var ds = doc.scrollTop();
  var of = vh / 4;

  // if the panel is in the viewport, reveal the content, if not, hide it.
  for (var i = 0; i < panel.length; i++) {
    if (panel.eq(i).offset().top < ds+of) {
     panel
       .eq(i)
       .find('.panel__content')
       .addClass('panel__content--active');
    } else {
      panel
        .eq(i)
        .find('.panel__content')
        .removeClass('panel__content--active')
    }
  }
};

var scrolly = function(e) {
  e.preventDefault();
  var target = this.hash;
  var $target = $(target);

  $('html, body').stop().animate({
      'scrollTop': $target.offset().top
  }, 300, 'swing', function () {
      window.location.hash = target;
  });
}

var init = function() {
  burger.addEventListener('click', openMenu, false);
  window.addEventListener('scroll', scrollFx, false);
  window.addEventListener('load', scrollFx, false);
  $('a[href^="#"]').on('click',scrolly);
};

doc.on('ready', init);

http://codepen.io/anon/pen/ygamdE

My goal is to automatically hide the menu when a list item is clicked after opening the menu. How can I achieve this behavior? The jQuery hide function doesn't seem to work for me.

Answer №1

If you need to toggle the menu state in your project, utilize the existing openMenu() function which handles the opening and closing of the menu. Simply call this function within scrolly() after the browser has finished animating the user to the specified position on the page. For more details, check out: http://codepen.io/anon/pen/VPmZYe

var menu = document.querySelector('.nav__list');
var burger = document.querySelector('.burger');
var doc = $(document);
var l = $('.scrolly');
var panel = $('.panel');
var vh = $(window).height();

var openMenu = function() {
  burger.classList.toggle('burger--active');
  menu.classList.toggle('nav__list--active');
};

// reveal content of first panel by default
panel.eq(0).find('.panel__content').addClass('panel__content--active');

var scrollFx = function() {
  var ds = doc.scrollTop();
  var of = vh / 4;
  
  // if the panel is in the viewport, reveal the content, if not, hide it.
  for (var i = 0; i < panel.length; i++) {
    if (panel.eq(i).offset().top < ds+of) {
     panel
       .eq(i)
       .find('.panel__content')
       .addClass('panel__content--active');
    } else {
      panel
        .eq(i)
        .find('.panel__content')
        .removeClass('panel__content--active')
    }
  }
};

var scrolly = function(e) {
  e.preventDefault();
  var target = this.hash;
  var $target = $(target);

  $('html, body').stop().animate({
      'scrollTop': $target.offset().top
  }, 300, 'swing', function () {
      window.location.hash = target;
  });
  openMenu();
  
}

var init = function() {
  burger.addEventListener('click', openMenu, false);
  window.addEventListener('scroll', scrollFx, false);
  window.addEventListener('load', scrollFx, false);
  $('a[href^="#"]').on('click',scrolly);
};

doc.on('ready', init);
* {
  box-sizing: border-box;
}

body {
  font-family: 'Montserrat';
  line-height: 1.5;
  -webkit-font-smoothing: antialiased;
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.nav {
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  width: 100px;
  -webkit-backface-visibility: hidden;
          backface-visibility: hidden;
}
.nav__list {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-flow: column wrap;
      flex-flow: column wrap;
  height: 85vh;
  -webkit-transform: translate(0, -100%);
          transform: translate(0, -100%);
  -webkit-transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.nav__list--active {
  -webkit-transform: translate(0, 0);
          transform: translate(0, 0);
}
.nav__item {
  -webkit-box-flex: 1;
      -ms-flex: 1;
          flex: 1;
  position: relative;
}
.nav__link {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  text-decoration: none;
  font-size: 24px;
  background: #2b3033;
  -webkit-transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.nav__link:hover {
  background: #272b2e;
}
@media (max-width: 640px) {
  .nav {
    width: 70px;
  }
  .nav__list {
    height: 90vh;
  }
}

.burger {
  height: 15vh;
  position: relative;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  z-index: 2;
  background: #2b3033;
  cursor: pointer;
  -webkit-transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.burger:hover {
  background: #272b2e;
}
.burger__patty {
  position: relative;
  height: 2px;
  width: 40px;
  background: white;
}
.burger__patty:before {
  content: "";
  position: absolute;
  top: -10px;
  left: 0;
  height: 2px;
  width: 100%;
  background: white;
}
.burger__patty:after {
  content: "";
  position: absolute;
  top: 10px;
  left: 0;
  height: 2px;
  width: 100%;
  background: white;
}
.burger__patty, .burger__patty:before, .burger__patty:after {
  will-change: transform;
  -webkit-transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.burger--active .burger__patty {
  -webkit-transform: rotate(90deg);
          transform: rotate(90deg);
}
.burger--active .burger__patty:before {
  -webkit-transform: rotate(-45deg) translate(-7px, -7px) scaleX(0.7);
          transform: rotate(-45deg) translate(-7px, -7px) scaleX(0.7);
}
.burger--active .burger__patty:after {
  -webkit-transform: rotate(45deg) translate(-7px, 7px) scaleX(0.7);
          transform: rotate(45deg) translate(-7px, 7px) scaleX(0.7);
}
@media (max-width: 640px) {
  .burger {
    height: 10vh;
  }
  .burger__patty {
    -webkit-transform: scale(0.8);
            transform: scale(0.8);
  }
  .burger--active .burger__patty {
    -webkit-transform: scale(0.8) rotate(90deg);
            transform: scale(0.8) rotate(90deg);
  }
}

.panel {
  min-height: 100vh;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  overflow: hidden;
}
.panel__wrapper {
  padding: 7vh 7vw;
  -webkit-perspective: 1000px;
          perspective: 1000px;
}
.panel__content {
  will-change: transform;
  -webkit-transform: scale(0.7) rotateX(-230deg);
          transform: scale(0.7) rotateX(-230deg);
  -webkit-transform-origin: center 80%;
          transform-origin: center 80%;
  opacity: 0;
  -webkit-transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.panel__content--active {
  -webkit-transform: none;
          transform: none;
  opacity: 1;
}
.panel__headline {
  font-weight: 700;
  opacity: 0.8;
  font-size: 48px;
  margin: 0 0 25px 0;
}
.panel p {
  margin: 0 0 25px 0;
  color: #1a1a1a;
  font-size: 24px;
  max-width: 800px;
}
.panel p:last-child {
  margin-bottom: 0;
}
@media (max-width: 640px) {
  .panel__headline {
    font-size: 36px;
  }
  .panel__wrapper {
    padding: 10vh 10vw;
  }
  .panel p {
    font-size: 16px;
  }
}

.c-blue {
  color: #5fc7ea;
}

.c-red {
  color: #e68568;
}

.c-green {
  color: #68e6ac;
}

.c-yellow {
  color: #e6d068;
}

.b-blue {
  background: #5fc7ea;
}

.b-red {
  background: #e68568;
}

.b-green {
  background: #68e6ac;
}

.b-yellow {
  background: #e6d068;
}

.logo {
  position: fixed;
  bottom: 3vh;
  right: 3vw;
  z-index: 2;
}
.logo img {
  width: 65px;
  -webkit-transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  -webkit-transform: rotate(0);
          transform: rotate(0);
}
.logo img:hover {
  -webkit-transform: rotate(180deg) scale(1.1);
          transform: rotate(180deg) scale(1.1);
}
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">

<meta name="viewport" content="width=device-width">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="nav">
  <div class="burger">
    <div class="burger__patty"></div>
  </div>

  <ul class="nav__list">
    <li class="nav__item">
      <a href="#1" class="nav__link c-blue"><i class="fa fa-camera-retro"></i></a>
    </li>
    <li class="nav__item">
      <a href="#2" class="nav__link c-yellow scrolly"><i class="fa fa-bolt"></i></a>
    </li>
    <li class="nav__item">
      <a href="#3" class="nav__link c-red"><i class="fa fa-music"></i></a>
    </li>
    <li class="nav__item">
      <a href="#4" class="nav__link c-green"><i class="fa fa-paper-plane"></i></a>
    </li>
  </ul>
</nav>

<section class="panel b-blue" id="1">
  <article class="panel__wrapper">
    <div class="panel__content">
      <h1 class="panel__headline"><i class="fa fa-camera-retro"></i>&nbsp;Cameras</h1>
      <div class="panel__block"></div>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ea molestias ducimus, eos asperiores, ab officia sint nostrum quia, corporis officiis id praesentium expedita numquam ad non error optio est in.</p>
    </div>
  </article>
</section>
<section class="panel b-yellow" id="2">
  <article class="panel__wrapper">
    <div class="panel__content">
      <h1 class="panel__headline"><i class="fa fa-bolt"></i>&nbsp;Lightning</h1>
      <div class="panel__block", gt;</div>
      <p>Paleo authentic mlkshk taxidermy, vinyl meditation lomo drinking vinegar sartorial raw denim Thundercats bitters selvage listicle. Keffiyeh Williamsburg gastropub McSweeney's.</p>
    </div>
  </article>
</section>
<section class="panel b-red" id="3">
  <article class="panel__wrapper">
    <div class="panel__content">
      <h1 class="panel__headline"><i class="fa fa-music"></i>&nbsp;Music</h1>
      <div class="panel__block"></div>
      <p>Beard sriracha kitsch literally, taxidermy normcore aesthetic wayfarers salvia keffiyeh farm-to-table sartorial gluten-free mlkshk. Selvage normcore 3 wolf moon, umami Kickstarter artisan meggings cardigan drinking vinegar bicycle rights.</p>
    </div>
  </article>
</section>
<section class="panel b-green" id="4">
  <article class="panel__wrapper">
    <div class="panel__content">
      <h1 class="panel__headline"><i class="fa fa-paper-plane"></i>&nbsp;Paper Planes</h1>
      <div class="panel__block"></div>
      <p>90's wayfarers lomo you probably haven't heard of them trust fund banh mi. Flannel Shoreditch dreamcatcher, quinoa flexitarian Banksy pickled post-ironic lo-fi. Photo booth asymmetrical tousled letterpress.</p>
    </div>
  </article>
</section>
<a href="http://ettrics.com/code/vertical-layout-navigation/" class="logo" target="_blank">
 <img class="logo" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/45226/ettrics-logo.svg" alt="" /> 
</a>

Answer №2

I'm getting the impression that you'd like the menu to close when a navigation item is clicked.

Within your initialization function, include an event listener for the menu. This listener should trigger the openMenu() function, which will in turn toggle the nav_list.

var init = function() {
  menu.addEventListener('click', openMenu, false);
  burger.addEventListener('click', openMenu, false);
  window.addEventListener('scroll', scrollFx, false);
  window.addEventListener('load', scrollFx, false);
  $('a[href^="#"]').on('click',scrolly);
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery - Designing a customizable slider for rating a product or service

Currently, I am in the process of creating a web page utilizing jQuery that requires users to rate something on a scale. This rating scale would involve users selecting a number between 0 and 1 to reflect their knowledge on a particular topic. Instead of a ...

Determine if the JSON lacks an array within it

Utilizing an API to fetch results, the response received looks something like the following: {"currentPage":1,"numberOfPages":1,"totalResults":1,"data":[{"id":"Sf8xxo","name":"The Bear Reader Huckleberry Oatmeal Stout","nameDisplay":"The Bear Reader Huckl ...

Upon inserting Node 5, an error with the code EINVALIDTYPE occurred in npm

Recently, after I upgraded to Node 5, I've been encountering an error in the terminal every time I try running anything with npm. npm -v: 2.14.12 Desperately attempting to update npm to the latest version: MacBook-Pro-de-MarceloRS:promo-auto-loan ...

Vue-resource is returning a Promise object

How do I access the response data in an Ajax call? When I log response.text(), it displays a PromiseObj. Console PromiseObj context: undefined promise: Promise {status: "resolved", result: ")]}',↵{\"Result\":\"SUCCESS\",&bs ...

Dealing with Regular Expressions in Javascript and PHP Challenge

I am struggling to achieve the same outcome with my JavaScript as I do with my PHP code. The issue lies in how JavaScript omits backslashes, unlike PHP. To address this, I have included random forward and backward slashes to cater for different systems. Se ...

Node.js captures the Promise and provides detailed feedback

As I embark on my journey with Node.js + Express, currently in the process of structuring my HTTP APIs, I have a controller that utilizes a specific pattern: my_controller.js 'use strict'; var AppApiFactory = function (express, appService) { ...

Guide on how to toggle disabled input text box upon checking checkbox using JavaScript

When the checkbox next to the appended text box is checked, I want to disable that text box. The hard-coded text box is already disabled when its checkbox is checked. You can see the actual outcome by running the code snippet or check out the screenshots b ...

Ways to showcase additional content

When I receive a JSON Object containing posts from a WordPress account, it only includes about 15 posts. What steps can I take to retrieve more than that amount? The structure of the JSON data is as follows: { ID: 4164, title: "24 Hour Non-Stop with Ma ...

Display multiple markers on a Google Map using google-map-react library

I am currently struggling to display markers on my Google Map using the map function. I have tried various approaches but nothing seems to work. Could there be limitations that I'm not aware of, or am I overlooking something critical? I experimented w ...

Ways to solely cache spa.html using networkfirst or ways to set up offline mode with server-side rendering (SSR)

I am facing an issue with my application that has server-side rendering. It seems like the page always displays correctly when there is an internet connection. However, I am unsure how to make Workbox serve spa.html only when there is no network available. ...

Generating dynamic content in a text field based on user selection from a dropdown menu using PHP

I have a database with two fields: package_title and package_cost. I am currently displaying the package_title in a dropdown menu using a while loop. When a customer selects a package_title from the dropdown, I would like to show the corresponding cost (pa ...

Utilize external URL in trigger.io's custom UIWebView component

I'm in the process of transitioning my existing backbone application, designed for a native iOS UIWebView, over to trigger.io in order to utilize its image caching and camera access features. The goal is to make this migration quickly and efficiently. ...

Is it possible to pass multiple API props to a NextJs Page at once?

I am currently facing a challenge in rendering a page that requires data from two different API fetches. The URL in the address bar appears as: http://localhost:3000/startpage?id=1 Below is the code snippet for the first API fetch: import { useRouter } f ...

Issues with the functionality of the map method in Javascript arrays

I have integrated Laravel and Vue.js to develop a chat application. To secure my response in Laravel, I implemented encryption to prevent unauthorized access from the console: public function get() { $contacts = User::where('id', '!=&ap ...

Resizing columns in HTML table remains effective even after the page is refreshed

I've created HTML pages with tables that have multiple columns, but I'm experiencing an issue. The columns are not resizable until I refresh the page. Could someone assist me in fixing this problem and explaining why it's happening? ...

Steps to fix issues with Cross-Origin Read Blocking (CORB) preventing cross-origin responses and Cross Origin errors

var bodyFormData = new FormData(); bodyFormData.set("data", "C://Users//harshit.tDownloads\\weather.csv"); bodyFormData.set("type", "text-intent"); //axios.post("https://api.einstein.ai/v2/language/datasets/upload", axio ...

Issue: parsing error, only 0 bytes out of 4344 have been successfully parsed on Node.js platform

I've been attempting to utilize an upload program to transfer my files. The specific code I'm using is as follows: app.post('/photos',loadUser, function(req, res) { var post = new Post(); req.form.complete(function(err, fields, fil ...

When the property "a" is set to true, it must also require the properties "b" and "c" to be included

I'm looking for a way to modify the following type structure: type Foo = { a: boolean; b: string; c: string; } I want to change it so that if a is true, then both b and c fields are required. However, if a is false or undefined, then neither b ...

Using PHPMailer to send form data via AJAX submission

I'm trying to use AJAX to submit a form and display PHP response on the same page at this link. I am working with Joomla using the Helix 3 framework, with jQuery version 1.12.4. The Helix 3 framework is based on Bootstrap 3. Here are the scripts that ...

Combining PHP JQuery Dialog with Datatables results in a sleek design loss

Recently, I encountered an issue with my code. I have a file called incident_view.php which pulls data from the database and displays it using Datatables. Everything was working fine until I tried to open this page in a JQuery dialog on another page called ...