Open the navigation menu by clicking on either the navigation links or anywhere outside of it

Seeking a solution for my mobile navigation menu that closes when clicking outside the links or on one of them, without using jQuery. How can I achieve this with JavaScript ES6?

Current code snippet:

const navSlide = () => {
    const burger = document.querySelector('.burger');
    const nav = document.querySelector('.nav-links');


    burger.addEventListener('click', () => {
        nav.classList.toggle('nav-active');
    })


}

navSlide();
html {
  scroll-behavior: smooth;
}

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  font-family: Gelion;
  background-color: #fa555204;
}

.nav-links li a, .logo {
  text-decoration: none;
 }
 
 ul {
  list-style: none;
}

.main-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 18px;
  height: 10%;
  padding: 20px 0;
}

.nav-links {
  display: flex;
}

.nav-links li {
  padding: 0 15px;
}

.burger{
  display: none;
}

/* Media Query - Mobile */

@media only screen and (max-width: 700px) {
    body {
      overflow-x: hidden;
    }

    /* Burger Menu */

    .nav-links {
      position: fixed;
      right: 0;
      height: 100vh;
      width: 60%;
      top: 0vh;
      background-color: var(--secondary-color);
      display: flex;
      justify-content: space-evenly;
      align-items: center;
      flex-direction: column;
      transform: translateX(100%);
      transition: transform 0.5s ease-in;
      z-index: 1;
    }

    .nav-links li a {
      color: #fff;
    }

    .nav-active {
      transform: translateX(0%);
    }

    .main-nav .burger {
      display: block;
      cursor: pointer;
      font-size: 35px;
    }
  }
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet"/>

<nav class="main-nav">
        <a href="#" class="logo" />Logo</a>
        <ul class="nav-links">
          <li><a href="#Overview">Overview</a></li>
          <li><a href="#Contagion">Contagion</a></li>
          <li><a href="#Symptoms">Symptoms</a></li>
          <li><a href="#Prevention">Prevention</a></li>
          <li><a href="#Contact">Contact</a></li>
        </ul>
        <div class="burger">
          <i class="fas fa-bars"></i>
        </div>
      </nav>

Answer №1

Applying CSS with ease by utilizing the :focus Selector is a simplified process. Refer to this resource for detailed information: https://www.w3schools.com/cssref/sel_focus.asp

Alternatively, you can also try the following:

.classname:focus{
  //your code here will be executed when the client focuses on this class
}

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

Is there a compelling case for implementing Meteor in 2017?

Back in the day, Meteor was expected to revolutionize web development on node by simplifying the process of creating interactive applications. Though I'm not well-versed in its history, it seems like most of the development effort has shifted elsewher ...

A step-by-step guide on how to exclusively print items that have been selected using a checkbox in AngularJS

I have created two tables and added a checkbox for each one. Instead of default checkboxes, I have used images that change when clicked. Here is the code snippet: <button class="btn btn-lg btn-customPrint-md no-print" ng-click="checkBoxPrint2 = !check ...

What is the best way to display both an employee's name and ID on a single line using CSS and HTML?

I am currently working on an asp.net MVC app and facing an issue with adding employee ID and employee name on the same line, similar to the web design provided. I need to make modifications using HTML and CSS to achieve this. The problem is that I am unab ...

Combine TypeScript files in a specific sequence following compilation

I am hoping to utilize gulp for the following tasks: Compiling TypeScript to JavaScript, which is easily achievable Concatenating JavaScript files in a specific order, proving to be challenging Since I am developing an Angular application, it is crucial ...

Adapting my JavaScript code to handle one-dimensional CSV data instead of the usual two-dimensional format

How can I effectively parse this CSV file using JavaScript? 1363085391,42.890000000000,5.432200000000 1363088879,47.570000000000,4.981800000000 1363120475,56.560000000000,1.768000000000 1363132522,53.000000000000,1.000000000000 1363214378,48.630000000000, ...

Providing UI field attributes within server JSON data

Suppose I have numerous form fields that need to be displayed on the user interface. Additionally, in a standard Modify workflow, let's assume that these fields will have various attributes like value, mandatory, editable, disabled, label, regex (for ...

Exploring the Ways to Share sessionStorage Across Multiple Browser Tabs Using JavaScript

I have recently started exploring client-side data storage and have successfully implemented an onkeyup search function. The goal is to retrieve the city name via AJAX and display it at the top within the header of the page. To store the city name, I have ...

jQuery Summation: A Step-by-Step Guide

Hello everyone, I am a new member of this forum and I am looking forward to learning and contributing with all of you. I have encountered a problem that I tried to solve on my own but couldn't figure it out. Would anyone be able to lend me a hand? H ...

Jquery onchange event fails to fire

$('#selectclassid').trigger("change"); $('#selectclassid').on('change', function() { }); When trying to manually trigger the onchange event, it does not seem to be firing as expected. Although this format is commonly seen ...

Encountered a 'SyntaxError: await is only valid in async function' error while trying to utilize the top-level await feature in Node v14.14.0

I'm excited to use the new top-level await feature that was introduced in Node version 14.8. For more information, you can check out this link and here. I did a thorough search but couldn't find any questions related to issues with the new featur ...

I can't believe this ReactJs project generated this code automatically

What does this automatically generated code do in my ReactJs app and what are the advantages of including it? <div class="nsc-panel nsc-panel-compact nsc-hide"> <div class="nsc-panel-move"></div> <div class=" ...

terminate the express middleware and return a custom HTTP status code

Is it possible to use custom middleware to return a 404 or 401 error to the user and prevent other handlers from running? I tried implementing the following code: function SomeMiddleware(req, res, next) { if(user.notRealOrSomething) { throw new Htt ...

The expression `Object.prototype.toString.call(currentFruit) === "[object Date]"` checks if the object referenced by `current

Hi, I'm just starting to learn JavaScript and I have a question about an if condition that I came across in my code. Can someone please explain what this specific if condition does? Object.prototype.toString.call(currentFruit) === "[object Date]& ...

JavaScript Hangman Game Malfunctioning

I am in the process of creating a basic hangman game to be played on a web browser. Whenever the user clicks a button, it triggers a function called pickWord(): <button onclick="pickWord()" id="restart">Choose A Word</button> This functi ...

Retrieve the nth element from an array using a function that requires 2 arguments

During my coding journey, I encountered a challenge that has proven to be quite tricky. The task in question goes as follows: Create a function that accepts an array (a) and a value (n) as parameters Identify and store every nth element from the array in ...

Request with an HTTP header for authentication

Here's a straightforward question that may seem simple to some developers but could be tricky for beginners. So, my question is - how can I send an HTTP request from a browser when a user clicks a button and also add an authorization header to the re ...

I am attempting to create a password validation system without the need for a database, using only a single

Help Needed: Trying to Create a Password Validation Website <script language="Javascript"> function checkPassword(x){ if (x == "HI"){ alert("Just Press Ok to Continue..."); } else { alert("Nope... not gonna happen"); } } ...

Sending Svelte data to Javascript with an onclick event

In my Svelte store, I have an ASCII-Logo that I want to integrate into a button spanning two symbols ("-."). However, I do not want to split the ASCII into separate parts and just insert the button between them on my +page.svelte. Currently, I h ...

Is there a way to implement Bootstrap 5 toast in Vue.js and navigate to a different page, such as after submitting a form?

Is there a way to incorporate the bootstrap5 toast in vuejs while also redirecting to another page? For example, after submitting a form and being redirected to a new page, I would like a toast message to appear with the statement "Your form has been sub ...

Using JQuery, retain only the initial N elements in a list and discard the rest

I'm looking to streamline a list of items in the DOM by keeping only the first N items, ideally through the use of slice and remove methods. Could someone provide me with the JQuery syntax for removing items that come after the first N in the list? ...