The showdown: JQUERY $(document).click versus $(document).ready

$(document).ready(function(e) {
  if ($('#sidebar').hasClass('active')) {
    $('#dismiss, .overlay').on('click', function() {
      $('#sidebar').removeClass('active');
      $('.overlay').removeClass('active');
    });
  } else {
    $('#sidebarCollapse').on('click', function() {
      $('#sidebar').addClass('active');
      $('.overlay').addClass('active');
      $('.collapse.in').toggleClass('in');
      $('a[aria-expanded=true]').attr('aria-expanded', 'false');
    });
  }
});
.fixed-top {
  z-index: 1 !important;
}

#sidebar {
  width: 250px;
  position: fixed;
  top: 0;
  left: -250px;
  height: 100vh;
  z-index: 999;
  background: #7386D5;
  color: #fff;
  transition: all 0.3s;
  overflow-y: hidden;
  box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.2);
}

#sidebar.active {
  left: 0;
}

#dismiss {
  width: 35px;
  height: 35px;
  line-height: 35px;
  text-align: center;
  background: #7386D5;
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
  -webkit-transition: all 0.3s;
  -o-transition: all 0.3s;
  transition: all 0.3s;
}

#dismiss:hover {
  background: #fff;
  color: #7386D5;
}

.overlay {
  display: none;
  position: fixed;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.7);
  z-index: 998;
  opacity: 0;
  transition: all 0.5s ease-in-out;
}

.overlay.active {
  display: block;
  opacity: 1;
}

#sidebar .sidebar-header {
  padding: 0px;
  background: #6d7fcc;
  text-align: center;
}

#sidebar ul.components {
  padding: 20px 0;
  border-bottom: 1px solid #47748b;
}

#sidebar ul p {
  color: #fff;
  padding: 10px;
}

#sidebar ul li a {
  padding: 10px;
  font-size: 1.1em;
  display: block;
}

#sidebar ul li a:hover {
  color: #7386D5;
  background: #fff;
}

#sidebar ul li.active>a,
a[aria-expanded="true"] {
  color: #fff;
  background: #6d7fcc;
}

a[data-toggle="collapse"] {
  position: relative;
}

.dropdown-toggle::after {
  display: block;
  position: absolute;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
}

ul ul a {
  font-size: 0.9em !important;
  padding-left: 30px !important;
  background: #6d7fcc;
}

ul ul ul a {
  font-size: 0.7em !important;
  padding-left: 40px !important;
  background: #6d7fcc;
}

ul.CTAs {
  padding: 20px;
}

ul.CTAs a {
  text-align: center;
  font-size: 0.9em !important;
  display: block;
  border-radius: 5px;
  margin-bottom: 5px;
}

a.download {
  background: #fff;
  color: #7386D5;
}

a.article,
a.article:hover {
  background: #6d7fcc !important;
  color: #fff !important;
}
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />

<nav id="sidebar">
  <div class="sidebar-header">
    <div id="dismiss">
      <i class="fas fa-arrow-left"></i>
    </div>
  </div>
</nav>

<nav class="navbar navbar-expand-lg navbar-light fixed-top" style="background-color:#6d7fcc;">
  <div class="container-fluid">
    <button type="button" id="sidebarCollapse" class="btn btn-info">
      <i class="fas fa-align-left"></i>
      <span>Table Of Contents</span>
    </button>
  </div>
</nav>

<div class="overlay"></div>

while using the

$(document).ready(function (e){...});
code, the button for opening the sidebar is functional, but the dismiss button does not respond as expected.

when changed to

$(document).click(function (e) {...});
, the dismiss button works, but I have to click the toggle button twice initially to open the sidebar. Why is this happening?

Furthermore, I need assistance in closing the sidebar when clicking outside of it. I have the following code:

$(document).click(function(e) {
    if ($('#sidebar').hasClass('active') && !$(e.target).is('#sidebar')) {
        $('#sidebar').removeClass('active');
        $('.overlay').removeClass('active');
    }
});

although I have edited the code, it does not achieve the desired function.

Any help or insight on this issue would be greatly appreciated. Additionally, the imports of bootstrap files have been properly organized in the code.

Answer №1

Within your code, the if statement is being evaluated when the document is in the ready state.

To solve the issue, you should move the code responsible for hiding the sidebar outside of the if condition.

Instead, you can check for the presence of the active class on #sidebar within the click function.

$('#dismiss, .overlay').on('click', function() {
    if ($('#sidebar').hasClass('active')) {
        $('#sidebar').removeClass('active');
        $('.overlay').removeClass('active');
    }
});

$('#sidebarCollapse').on('click', function() {
    if (! $('#sidebar').hasClass('active')) {
        $('#sidebar').addClass('active');
        $('.overlay').addClass('active');
        $('.collapse.in').toggleClass('in');
        $('a[aria-expanded=true]').attr('aria-expanded', 'false');
    }
});

In other words, you should tie the if condition to the click event.

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

Encountering difficulties in retrieving the JSON data from the web service

My external web service contains JSON data which has been validated using the JSON Validator website. However, I am facing an issue where the success function in the code below is not running at all. The web service necessitates that the email and password ...

Deleting items with a swipe gesture in Angular 10

Hey there, fellow developer! I could really use some assistance in implementing the swipe delete feature for our Angular project. Could you take a look at the screenshot provided below? https://i.sstatic.net/LqXlm.jpg The code snippet given to me for thi ...

Utilizing a media query to execute a <script> exclusively on desktop devices

I am attempting to only run <script type="text/javascript" src="#" data-cfasync="false" async="async"></script> on desktop devices. I experimented with <style> @media screen and (max-width: 600px) { ...

Form must transmit data to a controller in codeigniter

I'm currently working on a form that needs to post data to a function within the controller. The form contains two buttons that should send data to two different controller functions. Below is the HTML code for the form: <form> <input id="am ...

Which elements should I focus on when utilizing Media Query?

For the width specified in the CSS for various tags within my HTML, do I need to individually list each tag when setting CSS for a Media Query? If so, how can I do this while maintaining the same ratio for full screen? <!DOCTYPE html PUBLIC "-//W3C//DT ...

CSS hover effect: altering background colors of both parent and child elements simultaneously

HTML: <div class="container"> <div class="parent">one <div class="child">two</div> </div> </div> CSS: .parent { background: red; height: 200px; width: 200px; } .child { back ...

Retrieving the value of a <select> element using React.useState in a Nextjs environment

Encountering an issue in Nextjs involving the useState function from React. There is a select element with multiple options. Upon selection, the useState should store the value of the selected option. const [value, setValue] = useState('') ... ...

Center a single div vertically within a parent div by utilizing a fluid layout

Attempting to align text elements within a responsive layout presents challenges due to the fluid nature of <div> sizes. I recently discovered a fantastic method for horizontally and vertically centering a child <div> inside its parent <div ...

"Experiencing a callstack overflow due to multiple carousels on one page using Jquery or Vanilla

Currently, I am working on implementing a Jquery infinite autoplay multiple carousel. What I have done is created two separate carousel blocks on the same page within the body section. <div class="rotating_block"> <div class="bl ...

Tips for disabling scrolling on touch screens for input elements

I am facing an issue with a modal that is positioned on top of a scrollable document body. I am trying to prevent the scrolling of the document when I swipe my finger on the modal. $(document).on('touchstart touchmove', function(e){ e.preventDef ...

Alignment Troubles with Icons

I am having trouble positioning some icons on the far right of my 960 grid template header, next to my logo which is on the far left. I have tried multiple ways but can't seem to get it right. Any assistance would be greatly appreciated. Below is the ...

Disable page scrolling after making changes to the DOM

When my JavaScript function executes on page load and at set intervals, it cycles through images supplied by another PHP script. However, every time the function manipulates the DOM, the page scrolls back to the top of the containing div, which is quite fr ...

Troubleshooting common issues with PHP's simple HTML DOM parser

I've encountered an issue while working on a scraper for a website that involves crawling through links. The error message I'm receiving is as follows: PHP Fatal error: Uncaught Error: Call to a member function find() on null in D:\Projekti ...

Ways to deactivate the Bootstrap collapse feature

In my accordion FAQs, I am facing an issue where Question 1 is automatically opened when the page loads. Additionally, when I click on Question 2, it closes instead of staying open. I would like to address these problems and make sure that each question st ...

Phonegap Application: Page design gets distorted following keyboard input

After a user enters login details and the next page loads, the layout shifts as shown in the image below. The entire app layout breaks and the view moves down to accommodate the size of the onscreen keyboard. This issue persists unless the orientation is ...

Updating children of specified parents using jQuery

I have a collection of files in a directory and some file icons need to be changed as the default ones are not specific enough. Due to limitations, I can only achieve this using jQuery to insert the code since the mimetype function cannot be modified. Bel ...

Scroll down only if the user is not actively scrolling

Struggling with JavaScript once again and feeling frustrated! Can someone please assist me? I am currently working on a basic chat application that retrieves content from a text file using an AJAX request. The content refreshes every few seconds, scrollin ...

Dynamic population of dropdown not working as expected

Below is the code I am using to populate a Dropdown: $(document).ready(function(){ $('#inDistrict').sSelect(); $("#inDistrict").change(function(){ $.getJSON("filldistricts.php",{id: $(this).val(), ajax: 'true'}, function(j) ...

Animation for navigation | Struggling to animate only the specific list item

It's late at night and I'm struggling to solve a small problem. Despite feeling tired, I'll ask anyway - even if it makes me look foolish. Here is the code snippet: The HTML: <style> nav.main ul { font-size:175%; font-weight:300; ...

Understand which form has been submitted

I have eight Forms in a page (Form0, Form1, Form2 and so forth). Each form, when submitted, sends data to ReassignPreg.php using JavaScript, which then searches for the data in the database and returns it as JSON. The corresponding divs on the page are the ...