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

Guide to prompting a browser to download a file using an XHR request

When it comes to downloading files from a server using an XHR request, how can I ensure that the browser initiates the download once the response is received? Additionally, which headers should be included by the server for this process to work seamlessl ...

The functionality of the React Router DOM seems to be malfunctioning

I am facing an issue with running a program on my computer while it runs successfully on other PCs. When I try to run this program, I encounter the following error message. Any help in fixing this would be greatly appreciated... index.js import React, {C ...

Error: The object with the function (a, b) does not have the 'paresJSON' method available

I'm currently using jQuery to retrieve JSON data from a PHP file. The data is encoded in utf-8, and in order to decode it correctly (if I understood correctly), so that it doesn't display as \uXXX, I believe I need to use the parseJSON metho ...

HTML header with zero margin

Hi there! I am currently learning the basics of HTML and CSS. I have a question regarding creating a header with no margins on the edges. Any advice would be greatly appreciated as I haven't been able to find a clear solution. Below is my code snippet ...

Infinite scrolling feature on Kendo UI mobile listview showcasing a single item at a time

Currently, I am utilizing the kendo ui mobile listview and encountering an issue when setting endlessScroll or loadMore to true. The problem arises as the listview only displays the first item in such instances. Upon inspecting with Chrome inspector, I ob ...

What is the best way to create a mock URL in axios for unit testing purposes?

Scenario In this application, the URL is only accessible in production and cannot be accessed locally. During unit testing, it becomes necessary to mock the response from that URL. Solution Refer to this helpful tutorial for guidance. Current Implement ...

Unexpected behavior observed in JavaScript and AJAX functionality

In my web development project, I've decided to incorporate JavaScript and AJAX for the signup form functionality. However, I seem to be facing some challenges as I try to post all the textbox values from the signup form through AJAX. The code snippe ...

Steps for signing up for an event using addEventSource in fullCalendar

Whenever I click on the dayClick event, my goal is to add an event to the date that was clicked. This is the JavaScript code I currently have: $('#calendar').fullCalendar({ header: { center: "title", // The title appears in the center ...

Self-moving button container

I have a challenge involving a button and a sliding div. When the button is clicked, I want the div to slide. The problem arises when I place the button inside the sliding div - it ceases to slide. I understand the issue at hand, but I'm unsure of ho ...

What is the best way to nest a div within a flexbox container?

I am attempting to create a div that is based on percentages, and I want to nest a div inside another. Specifically, I want the center (xyz div) to only take up 90% of the height of the content-div. My goal is for the "content" div to be responsive to 90% ...

communicating data within a JavaScript file across server and client

One of my files, parameters.js, contains the following JavaScript code: const myJSON = { parameter1: 2, parameter2: 2. } module.exports = {myJSON} In another file called server.js, I can access this data by usin ...

translating xpath code into css styling

Can you help me with converting this xpath to css? By.xpath("//div[@id='j_id0:form:j_id687:j_id693:j_id694:j_id700']/div[2]/table/tbody/tr/td"); I've tried a couple of options, but none of them seem to work: By.cssSelector("div[@id=&apos ...

Create two div elements containing responsive images using HTML and CSS

Can someone assist me in creating responsive DIVs with images inside? Currently, the second div is appearing below the first one, and I'm struggling to make them scale based on mobile and tablet screen sizes. Here is the code snippet: .new_ba ...

Steps to create a fixed pattern background image with a customizable background color based on the content within a div element

I am seeking guidance on how to create a single page application using Angular that features a fixed background image (such as a white pattern) in the BODY tag. However, I would like the ability to change the color behind this image depending on the conten ...

Getting rid of all CSS properties currently set for the Mobile view

Utilizing third-party library components in my project. The library includes components that come with predefined styles for mobile devices. I am seeking to completely UPDATE these properties within my own code. When I say "update," I mean removing all th ...

In HTML, the usage of "*" and <body> element within a <style

Can you explain the distinction between * and body when used in the style tag of HTML? Providing examples would greatly aid my understanding. Thank you! ...

Attempting to execute a code snippet using Express framework on the local server at port 3000

Having some trouble with my initial attempt at a basic application. The Scraper.js file successfully scrapes a URL and outputs the array to the document object when executed in the console. Now, I want to set up an Express server to run the script whenever ...

Execute Javascript to simultaneously open various links in a single action (not using popups)

I am looking to open multiple URLs with a single click event that also redirects to a specified URL. I have attempted this, but it doesn't seem to be working as intended. Here is the HTML code: <a id="mybutton" href="http://example.net/quote" onc ...

Align your content perfectly on a full-screen slick slider

Attempting to center content over a full-screen slick slider from kenwheeler.github.io/slick/, I used a flexbox but the content remains at the edge of the viewport. It seems like an issue with the position tag in the slick CSS, but I can't figure out ...

Is there a way to position the twitter embed at the center of a webpage?

I am attempting to embed a Twitter video and twit in such a manner that they are perfectly centered on the page and also take up the entire width of the container (my-container). Here is the HTML code that I currently have: <div class="my-container"&g ...