Is there a way to prevent the slide-out bar from automatically hiding when selecting an item from its list?

I am facing an issue with my dashboard that has a slideout sidebar. Whenever I press the toggle button, the sidebar slides out as expected. However, when I click on any tab within the sidebar, it hides again. I only want it to hide when toggled. My code is functioning correctly, but I need to implement a feature to prevent the slide-out bar from hiding when a tab is clicked. When I press the toggle button, it should open like this:

But currently, clicking on any tab in the slideout sidebar (e.g., Home) causes it to hide again. It should only be hidden by toggling.

Answer №1

Your code is correct, but when you click the tabs, it may seem like the menu is toggling again because new pages are being loaded. Each page starts fresh with the menu closed since HTML requests are stateless and don't retain information about the previous page's open menu.

To work around this issue, you can record the open state of the panel (using a cookie or URL parameter) and check that value on each page load, or use Ajax to load only the necessary parts of the page (preferred).

Implementing the Ajax solution transforms your website into a Single Page Application (SPA), ensuring that the JavaScript running on the page is preserved.

The following example demonstrates adding a handler for the menu link. It captures the clicked link's href attribute and uses it to fetch the new page content using $.get(). The extracted content section of the page is then replaced within the existing page content div.

 $('#sidebar a').click(function(e){
     e.preventDefault();
     // Load the target URL using Ajax
     var href = $(this).attr("href");
     $.get(href, function(html){
         // Extract the content portion of the loaded page
         var content = $(html).find('.content');
         $('.content').replace(content);
     });
 });

JSFiddle: http://jsfiddle.net/TrueBlueAussie/f51k7eev/3/

Notes:

  • I updated your load handler to use a DOM ready handler, which is recommended for jQuery as it ensures the script runs after the DOM is fully loaded.
  • I removed unnecessary parseInt calls as jQuery's .width() returns a pixel value without the "px" suffix.

Issues: If you pursue the SPA approach, remember to update the browser address bar URL manually (e.g., using history.js) to avoid always returning to the initial page upon refresh.

Answer №2

I have updated the href attribute to "javascript:void" instead of linking to a specific page.

 $(window).load(function() {
   $("[data-toggle]").click(function() {
     var toggle_el = $(this).data("toggle");
     $(toggle_el).toggleClass("open-sidebar");
     if ($(toggle_el).hasClass("open-sidebar")) {
       console.log($('.content').width());
       console.log(parseInt($('.content').width()) - 240);
       $('.content').width(parseInt($('.content').width()) - 240);
     } else
       $(".content").css('width', '100%');
   });
   $(".swipe-area").swipe({
     swipeStatus: function(event, phase, direction, distance, duration, fingers) {
       if (phase == "move" && direction == "right") {
         $(".container").addClass("open-sidebar");
         return false;
       }
       if (phase == "move" && direction == "left") {
         $(".container").removeClass("open-sidebar");
         return false;
       }
     }
   });
 });
 body, html {
          height: 100%;
          margin: 0;
          overflow:hidden;
          font-family: helvetica;
          font-weight: 100;
      }
      .container {
          position: relative;
          height: 100%;
          width: 100%;
          left: 0;
          -webkit-transition:  left 0.4s ease-in-out;
          -moz-transition:  left 0.4s ease-in-out;
          -ms-transition:  left 0.4s ease-in-out;
          -o-transition:  left 0.4s ease-in-out;
          transition:  left 0.4s ease-in-out;
      }
      .container.open-sidebar {
          left: 240px;
      }

      .swipe-area {
          position: absolute;
          width: 50px;
          left: 0;
      top: 0;
          height: 100%;
          background: #f3f3f3;
          z-index: 0;
      }
      #sidebar {
          background: #DF314D;
          position: absolute;
          width: 240px;
          height: 100%;
          left: -240px;
          box-sizing: border-box;
          -moz-box-sizing: border-box;
      }
      #sidebar ul {
          margin: 0;
          padding: 0;
          list-style: none;
      }
      #sidebar ul li {
          margin: 0;
      }
      #sidebar ul li a {
          padding: 15px 20px;
          font-size: 16px;
          font-weight: 100;
          color: white;
          text-decoration: none;
          display: block;
          border-bottom: 1px solid #C9223D;
          -webkit-transition:  background 0.3s ease-in-out;
          -moz-transition:  background 0.3s ease-in-out;
          -ms-transition:  background 0.3s ease-in-out;
          -o-transition:  background 0.3s ease-in-out;
          transition:  background 0.3s ease-in-out;
      }
      #sidebar ul li:hover a {
          background: #C9223D;
      }
      .main-content {
          width: 100%;
          height: 100%;
          padding: 10px;
          box-sizing: border-box;
          -moz-box-sizing: border-box;
          position: relative;
      }
      .main-content .content{
          box-sizing: border-box;
          -moz-box-sizing: border-box;
      padding-left: 60px;
      width: 100%;
      }
      .main-content .content h1{
          font-weight: 100;
      }
      .main-content .content p{
          width: 100%;
          line-height: 160%;
      }
      .main-content #sidebar-toggle {
          background: #DF314D;
          border-radius: 3px;
          display: block;
          position: relative;
          padding: 10px 7px;
          float: left;
      }
      .main-content #sidebar-toggle .bar{
           display: block;
          width: 18px;
          margin-bottom: 3px;
          height: 2px;
          background-color: #fff;
          border-radius: 1px;   
      }
      .main-content #sidebar-toggle .bar:last-child{
           margin-bottom: 0;   
      }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div id="sidebar">
    <ul>
      <li><a href="javascript:void(0)">Home</a>
      </li>
      <li><a href="javascript:void(0)">Explore</a>
      </li>
      <li><a href="javascript:void(0)">Users</a>
      </li>
      <li><a href="javascript:void(0)">Sign Out</a>
      </li>
    </ul>
  </div>
  <div class="main-content">
    <div class="swipe-area"></div>
    <a href="#" data-toggle=".container" id="sidebar-toggle">
      <span class="bar"></span>
      <span class="bar"></span>
      <span class="bar"></span>
    </a>
    <div class="content">
      <h1>Creating Swipeable Side Menu For the Web</h1>
      <p>"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
        dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
    </div>
  </div>
</div>

Answer №3

One suggestion is to include the event.stopPropagation() method in your script.

<script type="text/javascript">
      $(document).ready(function(e){
        $("[data-toggle]").click(function(e) {
           e.stopPropagation();
           //add your custom code here 
        });
      });
</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

Creating a CSS full-width navigation menu

Recently, I came across a menu code on the web that seemed great. However, I wanted to make my menu responsive and full width. Since I am new to CSS and HTML, adjusting the menu code has been a bit of a challenge for me. .menu, .menu ul { list-style: ...

Reopen a Kendo UI dialog

Currently, I am utilizing Kendo UI, and my goal is to display a modal dialog when a button is clicked. The issue I am facing is that it works perfectly the first time around. However, upon closing the dialog and attempting to reopen it by clicking the butt ...

Tips for properly utilizing "require" in application.css with the Skeleton framework

I am currently working on implementing the skeleton-rails CSS framework into my application. Within the app/views/layouts/application.html.erb file, I have created containers and a list nav that require styling. Following the guidelines provided by the ske ...

Ensuring the presence of a bootstrap angular alert with protractor and cucumberJS

I am currently utilizing protractor, cucumberJS, and chai-as-promised for testing. There is a message (bootstrap alert of angularJS) that displays in the DOM when a specific button is clicked. This message disappears from the DOM after 6000 milliseconds. ...

What is the best way to transfer a "require" object to Jade in Node.js?

I have developed a node module that includes a simple JavaScript file. My goal is to utilize this JavaScript function within my jade file. In music.js, I am importing the "myplayer" module: var keystone = require('keystone'); exports = module.ex ...

How to display currency input in Angular 2

Is there a way to dynamically format input as USD currency while typing? The input should have 2 decimal places and populate from right to left. For example, if I type 54.60 it should display as $0.05 -> $0.54 -> $5.46 -> $54.60. I found this PLUNKER that ...

How can I gather information from members who have already signed up?

I have a form that submits data to the Angular Firebase database. Once the form is submitted, I want to display the previously submitted data in the form if the user signs in again. Below is my .ts file: import { Component, OnInit } from '@angular/c ...

What is the best way to determine in component.html whether the column type is equal to 1 to show the label text "Active,"

Having trouble checking the value of an object named ReportControl. If the column type is 1, display the label "active"; otherwise, display the label "not active" on reportcomponent.html. The data for the ReportControl object is as follows: {"reportId": ...

Utilizing jQuery's each() function to create a seamless loop of background images in a

Struggling with looping the background image in a slick slider? Check out the code snippet below. var json = [ { "img_url": "https://via.placeholder.com/500x500?text=1" }, { "img_url": "https://via.placeholder.com/500x500?text=2" }, { "img_url": "ht ...

Is there a way to retrieve the value of bindings in the component controller using Angular 1.5 and Typescript?

In my quest to develop a versatile left-hand menu component that can dynamically display different menu structures based on input strings, I stumbled upon an interesting challenge. By binding a string to the <left-hand-menu-component> element like so ...

Using ng-repeat to iterate over forms in AngularJS

I have implemented dynamic forms using the ng-repeat directive where form fields are generated based on the userid value. The requirement is that the add user button should be enabled only when all form fields are filled. However, currently the button rema ...

Adjust CSS classes as user scrolls using skrollr

I am currently facing an issue with the prinzhorn/skrollr plugin when trying to use removeClass/addClass on scroll function. I have attempted to find a solution but unfortunately, nothing has worked for me. <li class="tab col s3"><a data-800="@cl ...

The issue with $.parseJSON when encountering double quotes

Could someone please clarify why a JSON string with double quotes can disrupt the functionality of $.parseJSON? This example works: [{"type":"message","content":{"user":"tomasa", "time":"1321722536", "text":"asdasdasd"}}] And so does this one: [{"type" ...

Correct validation is not achieved when the "!" symbol is used in the matches function

I am working on a React and Next.js project where I am using Formik for handling forms and Yup for validations. One specific input field requires some validations to be performed. This field must be required, so if the user does not enter any information, ...

Python Selenium Webdriver: Issues with retrieving text content from hidden elements

I am interested in extracting data from Netflix that includes the following details: 1. Show Name 2. Season 3. Episode Name for each season 4. URL for each episode 5. Duration of each show. Selenium version: 3.141.0 Python version: 3.6.6, utilizing Chr ...

The instance does not have a definition for the property or method "foo" that was referenced during rendering

[Vue warn]: Property or method "modelInfo" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. Whenever I ...

Tips for implementing multiple middlewares in Next.js using the middleware.ts script

In the development of my Next.js project, I am exploring the implementation of multiple middleware without depending on external packages. Although I have seen examples of using a single middleware in Next.js with the next-connect package, I aim to achieve ...

Gather information from various entities using JavaScript

I am looking to parse data from an Object and save them in an array. Specifically, I aim to extract all the US shoe sizes and compile them into an array. However, when utilizing the filter method, it only retrieves the first item with the "us" value. { ...

vue-router incorrectly updates parameters upon reload

One question I have is related to routing in Vue.js: // routes.js { path: '/posts', name: 'Posts', component: PostsView }, { path: '/post/:post_id', name: 'PostRead', component: PostReadView, }, { pat ...

When provided with varied inputs, new Date() yields distinct values for various time zones

var date1 = "2015-03-29"; console.log(new Date(date1)); //Output:Sun Mar 29 2015 05:30:00 GMT+0530 (India Standard Time) var date2 = "1869-12-31"; console.log(new Date(date2)); //Output:Fri Dec 31 1869 05:53:20 GMT+0553 (India Standard ...