Shut the offcanvas using a button

I am having trouble closing the offcanvas using the close button inside the offcanvas itself. Currently, I can only close it with the button that I used to open it. What mistake did I make? Please refer to the code snippet below.

(function mainScript() {
  "use strict";

  const offcanvasToggle = document.querySelector('[data-bs-toggle="offcanvas"], [data-bs-dissmiss="offcanvas"]');
  const offcanvasCollapse = document.querySelector(".offcanvas-collapse");

  offcanvasToggle.addEventListener("click", function () {
    offcanvasCollapse.classList.toggle("open");
  });
})();
.offcanvas-collapse {
  position: fixed;
  top: 0;
  /* Height of navbar */
  bottom: 0;
  left: 100%;
  width: 30%;
  padding: 8px 8px;
  overflow-y: auto;
  visibility: hidden;
  background-color: #343a40;
  transition: transform 0.3s ease-in-out, visibility 0.3s ease-in-out;
}

.offcanvas-collapse.open {
  visibility: visible;
  transform: translateX(-100%);
}
    <div id="navbar" class="flex-wrap center">
      <div id="nav-toggler-wrapper">
        <button id="nav-toggler" aria-label="Menü" data-bs-toggle="offcanvas" aria-label="Toggle navigation">
          <span class="menu-label">Menu</span>
        </button>
      </div>
    </div>
    

  <div id="sidenav" class="offcanvas offcanvas-collapse">
    <div class="offcanvas-header flex-wrap center between">
      <button id="nav-toggler" data-bs-dissmiss="offcanvas" aria-label="Toggle navigation">
        <span class="menu-label">Close</span>
      </button>
    </div>
  </div>

Answer №1

It is important to utilize querySelectorAll rather than querySelector in this scenario, as you are attempting to select multiple elements and then use forEach to apply an eventListner to each one. Here is an example:

(function executeMainScript() {
  "use strict";

  const toggleElements = document.querySelectorAll('[data-bs-toggle="offcanvas"], [data-bs-dissmiss="offcanvas"]');
  const collapseElement = document.querySelector(".offcanvas-collapse");

  toggleElements.forEach(element => {
    element.addEventListener("click", function() {
      collapseElement.classList.toggle("open");
    });
  });

})();
.offcanvas-collapse {
  position: fixed;
  top: 0;
  /* Height of navbar */
  bottom: 0;
  left: 100%;
  width: 30%;
  padding: 8px 8px;
  overflow-y: auto;
  visibility: hidden;
  background-color: #343a40;
  transition: transform 0.3s ease-in-out, visibility 0.3s ease-in-out;
}

.offcanvas-collapse.open {
  visibility: visible;
  transform: translateX(-100%);
}
<div id="navbar" class="flex-wrap center">
  <div id="nav-toggler-wrapper">
    <button id="nav-toggler" aria-label="Menü" data-bs-toggle="offcanvas" aria-label="Toggle navigation">
          <span class="menu-label">Menu</span>
        </button>
  </div>
</div>


<div id="sidenav" class="offcanvas offcanvas-collapse">
  <div class="offcanvas-header flex-wrap center between">
    <button id="nav-toggler" data-bs-dissmiss="offcanvas" aria-label="Toggle navigation">
        <span class="menu-label">Close</span>
      </button>
  </div>
</div>

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

Utilizing /deep/ and the triple greater than symbol (>>>) within Angular 2

After researching the /deep/ and ::shadow selectors, I've come across conflicting information. In a discussion on Stack Overflow: What do /deep/ and ::shadow mean in a CSS selector? It was noted that Chrome has deprecated the /deep/ combinator and i ...

Encountered an issue while working with npm vue-cli

Operating System: Windows 10 Node Version: v8.9.2 NPM Version: 5.5.1 I successfully installed vue-cli using NPM, but encountered an error when trying to run 'npm run dev' command. Below is the error message: npm ERR! code ELIFECYCLE npm ERR! ...

Best Practices for Installing Webpack in a Client/Server Folder Structure

Working on a React Nodejs web application and in the process of figuring out how to bundle the frontend using webpack. This is how my project's structured: Where exactly do I need to install webpack and configure webpack.config.js? I've noticed ...

changing the value of a text input based on the selected option in a dropdown using ajax

I attempted to update the text input value with data from the database after selecting an option from the dropdown list. However, I encountered an issue where the data is not populating the text input field. <?php //Including the database configuration ...

Using JavaScript, extract current date from an API data

Here is an example of how the data from my API appears: const data = [{ "id": "1", "name": "Lesley", "creationDate": "2019-11-21 20:33:49.04", }, { "id": "2", "name": "Claude", "creationDate": "2019-11-21 20:33:09.397", }, { "i ...

What is the method for converting a JSON string into an [object][object] format using Angular 6?

Is there a way to transform the data shown below into the [[object][object]] structure using Angular 6? resultArray = [{Q_id: "5bbee2fbbb34b98be0464c73", opt_id: 111},{Q_id: "5bbee2fbbb34b98be0464c73", opt_id: 113}] ...

Karma test encountered a provider that could not be identified

I am working with a provider called $_ConfigProvider: (function (angular) { angular.module('app') .provider('$_Config', ConfigProvider); function ConfigProvider() { .... //routes definition } ConfigProvider.prot ...

Unable to display button image when using both id and style class in CSS

During my transition from Java 7 to Java 8, I've encountered a peculiar issue. Here's a brief explanation: In my FXML file, I have a button defined with style class button-red-big and id btnInput: <Button id="btnInput" fx:id="btnInput" align ...

"Enhance the user experience by enabling clickable preview files in dropzone

After working on my Django project, I have implemented the following: <link href="{% static 'media/dropzone/dist/min/dropzone.min.css' %}" type="text/css" rel="stylesheet" /> <form class="dropzone" id="my-media-dropzone" action="/some/u ...

Basic javascript doesn't trigger

Attempting to create a basic AJAX script for testing PHP functionality. However, experiencing issues as the expected output "here" is not appearing due to an error message regarding event.returnValue being deprecated in Chrome. Any insights on what may be ...

Secure the anchor ahead of the table row

Currently, I am generating my code dynamically using PHP and assigning the ID attribute from the database to the anchor href. This is how it looks: PHP <table> <tr><th>ID</th></tr> <?php if ($stmt = $mysqli->prepare("S ...

The functionality of smooth scrolling is not compatible with the overflow-y property

Looking to implement a smooth scroll feature, I came across an example online and tried to adapt it. Here's the code I'm working with: https://jsfiddle.net/4DcNH/144/ I've added specific conditions to the html and body elements (changing t ...

Creating a flexible grid layout with DIVs that share equal width dimensions

Struggling with my HTML and CSS code, I need a way to structure nested DIV blocks into a responsive grid where each block has the same width. Despite my efforts, nothing seems to work as expected. Currently, the nested DIVs are stacked vertically one on to ...

retrieve the data-initial-value's value through JavaScript

Hello, I am currently attempting to retrieve the text from this input field but all I'm getting is an empty value. <input type="text" class="quantumWizTextinputPaperinputInput exportInput" jsname="YPqjbf" autocomplete= ...

Exploring the incorporation of various local fonts in NextJs version 13

Having trouble adding multiple local fonts to nextjs 13. According to the instructions in the documentation, you should follow these steps for a single file. I attempted to import two files like this: import '@/styles/globals.css'; import localF ...

Struggling to iterate through placeholder information

I am currently working on a frontend component that is mapped out and contains some placeholder data. The data is being pulled from a JavaScript file. export const userInputs = [ { id: 1, label: "First Name", type: &qu ...

Tips for preserving the current DOM using Ajax, jQuery, and PhP

I made some changes to my page by adding new divs, and now I want to save all of it, replacing the old content. Example of the DOM body: <body> <div id="save_dom">Save</div> <div class="box">111</div> <div cla ...

Traverse the array of nested JSON objects in an iterative manner

I need to iterate through a JSON array object with the following structure: var myJSONObject = { "abc": { "prod_1": [ {"prod_ver" : "prod 1 ver 1"}, {"prod_ver" : "prod 1 ver 2"}, ], "prod_2": [ ...

Disable the swipe feature on a Bootstrap carousel to prevent users from navigating through slides on mobile devices. The attribute data-touch="

I've been attempting to deactivate the swipe function on my Bootstrap 4 carousel in my project, but it's proven to be quite challenging. Despite it being a basic carousel, I'm finding it difficult to turn off this feature. What am I missing ...

Unable to load JSON information into an ExtJS grid

I have exhausted all the solutions I found (there are many on Stackoverflow) in an attempt to fix my extjs store issue. Despite ensuring that the grid is displayed correctly, the data still refuses to show up. Feeling perplexed, I am sharing the "store" co ...