Tips for closing a sidecart by clicking outside of it

I am currently exploring how to implement the functionality of closing my sidecart when I click outside of it. Below is the script I am using:

   const toggler = document.getElementById('menu-toggle');
const cartWrapper = document.getElementById('wrapper');
var crossButton = document.getElementById('closeCart');

// Displaying Menu Cart
document.addEventListener('DOMContentLoaded', () => {

    toggler.addEventListener('click', toggleCart);
    crossButton.addEventListener('click', closeCart);
    
    function toggleCart(){
        cartWrapper.classList.toggle('menuDisplayed');
        cartWrapper.classList.toggle('menuDisplayedBgColor');
    }

    function closeCart(){
        cartWrapper.classList.toggle('menuDisplayed');
        cartWrapper.classList.toggle('menuDisplayedBgColor');
    }

});

toggler represents the button that opens the sidecart, cartWrapper is the sidecart, and crossButton is the button that closes the sidecart.

Here is an image of my sidecart:

https://i.sstatic.net/KcSIl.png

If you require additional information about my code, feel free to ask. Thank you!

Below is the HTML code for my sidecart:

    <!-- Sidebar Cart-->

<div id="wrapper">
  
<!-- Sidebar -->
<div id="sidebar-wrapper">
  <div class="container">
  <div class="row">
    <div class="col-md-6 mt-auto titleCart">
      <h2 class="titleText">YOUR CART</h2>
    </div>
    <div class="col-md-2" style="left:30%"> 
      <div class="crossIcon" id="closeCart">
        <span class="iconify closeIcon" data-icon="zmdi:close"></span>
      </div>
    </div>
    </div>
    </div>
      <ul class="sidebar-nav">

      <li class="cart-item">
        <div class="cart-item-img">
           <img src="imgProducts/guitar1.jpg" alt="">
        </div>
        <div class="cart-item-txt">
           <a class = "cart-item-name" href="#">Miyiagi Guitar</a>
            <span class="cart-item-price-qty">
                1 x 16.00
            </span>
        </div>        
        <button class="button deleteBtn"><i class="fa fa-trash-o" style="position:relative;font-size:24px; left:0;"></i></button>   
        </li>
      </ul>

    <div class="col-md-12" style="margin-top:4em;">
      <hr class="dividerLineCart">
      <div class="cart-total">
        <h2 class="cartTotal">Total: $0.00</h2>
      </div>
    </div>
      <div class="col-md-12 d-flex buttonsCartDiv">
        <a href="cart.php" href="cart.php" class="buttonViewCart"> View Cart </a>
        <a href="#" class="buttonCheckout" style="margin-right:0.5em;"> Check Out </a>
      </div>
  </div>
</div>

Here is my navigation bar which contains the button to toggle the sidecart:

<nav class="navbar fixed-top navbar-expand-md py-3 navbar-dark" style="background-color: rgba(41, 56, 61,0.65);font-family: Helvetica Neue,Helvetica,Arial,sans-serif;">
    <a class="navbar-brand" href="index.php">
        <img src="Images/charman logo white-trans.png" alt="Logo" style="height:50px;">
    </a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse justify-content-end" id="collapsibleNavbar">
    <ul class="navbar-nav">
      <li><hr class="dropdown-divider"></li>
      <li class="nav-item">
        <a class="nav-link" href="index.php">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="shop.php">Shop</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link" href="guitars.php"  id="navbarDropdownMenuLink" role="button"  aria-haspopup="true" aria-expanded="false">
        Guitars
      </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="electrical-type.php">Electrical</a>
          <a class="dropdown-item" href="acoustic-type.php">Acoustic</a>
          <a class="dropdown-item" href="basses-type.php">Basses</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="contact.php">Contact</a>
      </li> 
      <li class="nav-item">
        <a class="nav-link" id="has-divider" href="#" data-target="#modalRegister" data-toggle="modal">Sign Up
        <span class ="glyphicon glyphicon-user" aria-hidden="true" style="float:left;padding-right:0.4em;"></span>
       </a>
      </li>  
      <li class="nav-item">
        <a class="nav-link" id="has-divider2" href="#" data-target="#modalLogin" data-toggle="modal">Login
        <span class="glyphicon glyphicon-log-in" aria-hidden="true" style="float:left;padding-right:0.4em;"></span>
        </a>
      </li>
      <li class="nav-item">
        <a class="nav-link" id="menu-toggle"><span id="cart-text">Cart</span>
          <span class="glyphicon glyphicon-shopping-cart" style="transform: scaleX(-1)" aria-hidden="true"></span>
          <span class="badge badge-notify">0</span>
        </a>
      </li>            
    </ul>
  </div>  
</nav>

Answer №1

Simply utilize the EventListener on the elements that are appearing outside of the sideCart. By the way, if you are wondering where to click, you just have to include a click event listener outside of the cart. Once you do that, you're all set!

Answer №2


  if (cartWrapper.hasClass("menuDisplayed")) {
    $("body").on("click", function() {
           closeCart();
       });
       cartWrapper.on("click", function(event) {
            event.stopPropagation();
       });
 });

Answer №3

I hope this code snippet proves to be useful for your project.

<script>
    let sidebar = document.getElementById('sidebar-wrapper');
    let navbarTogglerButton = document.getElementById('toggler-button');

    window.document.addEventListener('click', (e) => {
        let clickedArea = e.path[e.path.length-6]

        if ( clickedArea == sidebar || e.path[0] == navbarTogglerButton) {
            cartWrapper.classList.toggle('menuDisplayed');
            cartWrapper.classList.toggle('menuDisplayedBgColor');
        }
        else {
            cartWrapper.classList.toggle('menuDisplayed');
            cartWrapper.classList.toggle('menuDisplayedBgColor');
        }
    });
</script>

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

An unexpected error occurred in NodeJS: It is not possible to adjust headers once they have been sent

Recently, I've been working on a nodejs project and encountered the error message "Can't set headers after they are sent" when trying to get a response from http://localhost:8080/api/user. Despite researching solutions on Stack Overflow, none of ...

PHTML file IIS handler

I was surprised by the lack of online results when searching for a solution to my issue. In my local PHP project, I am encountering problems with PHTML files not being parsed correctly by IIS. The 'phtml' type is not included in the module mappin ...

There seems to be an issue with the location.href function in the server-side code of

I'm encountering an issue in the code below where I am attempting to redirect to the login page, but it seems to not be functioning as expected. app.get('/current-pass', (req, res) => { res.sendFile(path.join(staticPath, "currentPass ...

Tips to ensure the div remains 100vh in height, even when empty

As I work on a simple webpage with a header, body, and footer, it's essential for me to ensure that the content takes up the entire height of the page using 100vh. However, if I only have plain text in the body section without any child tags, it ends ...

Changing Parameters in Absolutely Positioned Sections

I have successfully created a fixed header with a higher z-index than the body content, allowing the content to slide underneath it. To position the content div directly below the fixed header, I applied a position:relative and specified a top value. Init ...

Do not apply styling to a particular page in CSS and HTML

Utilize the teachable.com platform and take advantage of their code Snippets feature (refer to attached photo #1) https://i.stack.imgur.com/dW1lB.png I inserted the following code: div { direction: rtl; } To modify the website's direction to be ...

A guide on implementing arrow links in D3.js

i am struggling to add an arrow to one end of a link in my code. even though the links are functioning correctly, i can't seem to figure out how to draw arrows successfully. any assistance on how to implement this would be greatly appreciated. thank y ...

Unable to render a rectangle with React's canvas context.fillRect

Could anyone help me with drawing a rectangle using React? I'm having trouble getting it to work. I'm confused as to why the code below isn't showing a rectangle on the screen. class DrawingView{ constructor(props) { this.canva ...

Creating a feature in Angular JS that allows for each item in a list to be toggled individually

Looking for a more efficient way to toggle individual buttons without updating all at once? Check out this basic example where each button toggles independently by using ng-click="selected = !selected". Instead of updating all buttons at once, you can achi ...

Exploring the textures of an imported 3D model mesh with multiple materials in A-Frame and Three JS

Currently, I am exploring A-Frame using a 3D model imported from Blender. Some parts of this model contain multiple meshes with two or more materials assigned to them. It is easy for me to adjust the material properties of meshes with just one material. ...

Saving data inputted in a form using ReactJS and JavaScript for exporting later

What is the best way to save or export form input in a ReactJS/JS powered website? For example, if I have a form and want to save or export the data in a format like CSV after the user clicks Submit, what method should I use? Appreciate any advice. Thank ...

Shrink Font-Awesome icon sizes using a Node.js and Express.js web application

Currently, I am in the process of developing a website using node.js + express.js and implementing font-awesome for icons. The local hosting of Font-awesome has resulted in a 1.2 MB JS file [font-awesome.js], even though we are only utilizing 10-15 icons. ...

Rendering EJS templates and smoothly scrolling to a specific section on a webpage

I need to display my index page and automatically scroll down to the form section. One way I thought of doing this is by: app.post('/rsvp', (req, res) => { res.render('index/#rsvp', { errors: { email: 'Your email has already ...

Incorporating a search bar into a container in WordPress

I was trying to include a search form inside a div using the code below: printf( '<div class="entry"><p>%s</p>%s</div>', apply_filters( 'genesis_noposts_text', __( 'Try again below.', 'genesis&apo ...

Floating elements are misaligned and not laying out correctly

I've encountered an issue where the footer div is appearing behind the right-hand side div. I have a central container div with two floated divs next to each other, and the footer is separate. I've spent hours trying to fix it but can't figu ...

I tried utilizing the useState hook to store the value, but surprisingly, it failed to update

I am brand new to Reactjs and currently working on creating an address form that includes 3 select options for country, state, and city. I have implemented React hooks in my project, where the page fetches a list of countries upon initial load. Subsequentl ...

Tracking global click events in Vue.js can provide valuable insights into user interactions on your

While working with JavaScript, I was able to create this code for a popover. By clicking on the navbar-link element, the popover will appear or disappear. However, it would be great if I could close the popover by clicking anywhere on the screen (when the ...

React Intersection Observer not functioning properly

Hey there! I'm trying to create an animation where the title slides down and the left element slides to the right when scrolling, using the intersection observer. Everything seems to be fine in my code, but for some reason it's not working. Any t ...

Can a "fragile export" be generated in TypeScript?

Testing modular code can be challenging when you have to export things just for the purpose of testing, which can clutter your code and diminish the effectiveness of features like "unused variable" flags on compilers or linters. Even if you remove a usage ...

Ensure that the header stays centered on the page as you scroll horizontally

Below is a given code snippet: header { text-align: center; } /* This section is just for simulation purposes */ p.text { width: 20rem; height: 50rem; } <html> <body> <header> <h1>Page Title</h1> <detail ...