By default, the sidebar is open on desktop devices while closed on mobile devices

I am struggling to figure out how to set my sidebar/navigation content, using Bootstrap, to be expanded by default on desktop and closed by default on mobile with the icon only showing on mobile devices. Despite multiple attempts, I cannot seem to make this work.

<nav class="menu menu-open" id="theMenu">
      <div class="menu-wrap">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
          <i class="fa fa-bars menu-close d-lg-none" id="menu-toggle"></i>
            </button>
          <div id="menu-logo">
            <img src="Final_Logo.png" width="210" height="214" alt="">
          </div>
          <div id="navbarToggleExternalContent">
          <ul id="main-menu">
              <a href="#">Home</a>
              <a href="#">About</a>
              <a href="#">Writing</a>
              <a href="#">Events</a>
              <a href="#">Speaking</a>
              <a href="#">Music</a>
          </ul>
          <ul id="social-icons">
              <li class="facebook"><a href="#"><i class="fab fa-facebook fa-2x"></i></a></li>
              <li class="twitter"><a href="#"><i class="fab fa-twitter fa-2x"></i></a></li>
              <li class="instagram"><a href="#"><i class="fab fa-instagram fa-2x"></i></a></li>
          </ul>
        </div>
      </div>
  </nav>

Despite attempting to use this JavaScript code, it has not worked as expected:

 $('.menu-close').on('click', function(){
    $('#menuToggle').toggleClass('active');
    $('body').toggleClass('body-push-toright');
    $('#theMenu').toggleClass('menu-open');
    alert("Test");
    });

Answer №1

It seems like the solution can be found here: To implement this, simply include one of the navbar-expand-* classes in your <nav> element. For example:

<nav class="menu menu-open navbar-expand-md" id="theMenu">

Answer №2

Initially, let's address a few key points:

  1. Although you mentioned a sidebar, your code doesn't resemble a traditional sidebar; it appears more like a responsive topnav. I'll do my best to interpret it correctly and provide an example of a functional sidebar if that's what you intend.

  2. The menu items are within a <ul> (unordered list) without any <li> (list items). Bootstrap's JS/CSS typically requires the presence of <li> elements for proper functionality. While technically valid HTML, a <ul> should only contain <li> items, making sure any anchors or other content inside a <ul> are enclosed in <li> tags for validity.

  3. Your intentions with the social icons aren't clear, so I've made minor adjustments to their positioning for better alignment.

  4. I included overflow-y: scroll; on the <html> element to prevent shifting when the menu opens on small screens and creates a scrollbar. Depending on your site's design, this may not be necessary based on layout and content structure.


Let's start with a basic responsive menu setup:

Basic Bootstrap Responsive Menu

html {
  overflow-y: scroll;
}
.social {
  padding: 4px 8px;
}
Additional CSS/JS Links...


To enhance the menu with images and adjust the position of menu elements:

  1. Adjust the hamburger button to align at the bottom of the navbar by updating the positioning rule. You can modify the top: calc(100px - 1rem); to place it at the top or bottom of the nav depending on your preference.

  2. Position the menu items to rest at the bottom of the menu bar even when expanded.

  3. Position the social icons at the bottom-right corner for better visual balance.

  4. These adjustments specifically apply above the medium breakpoint (768px) in a media query to ensure proper positioning when the menu is open or closed.

Enhanced Menu with Image

Updated CSS Styles here...
Additional CSS/JS Links...


If you require a sidebar implementation, Bootstrap doesn’t inherently offer sidebar navigation. However, various tutorials exist online for creating sidebar layouts. I've utilized a basic version from popular resources to showcase an example here.

Collapsible Sidebar

Javascript function here...
Sidebar CSS styles defined here...
Additional CSS/JS Links...

Answer №3

One effective way to control the visibility of content on various viewport sizes or devices is by utilizing CSS Media Query.

Answer №4

Check out this link for exactly what you need. I have put together a pen just for you. Take a look at the link below.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<nav class="navbar navbar-expand-lg navbar-light bg-light" id="theMenu">
  <a class="navbar-brand" id="menu-logo">
            <img src="Final_Logo.png" width="210" height="214" alt="">
          </a>      
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav mr-auto" id="main-menu">
            <li class="nav-item"><a class="nav-link" href="#">Home</a></li>
            <li class="nav-item"><a class="nav-link" href="#">About</a></li>
            <li class="nav-item"><a class="nav-link" href="#">Writing</a></li>
            <li class="nav-item"><a class="nav-link" href="#">Events</a></li>
            <li class="nav-item"><a class="nav-link" href="#">Speaking</a></li>
            <li class="nav-item"><a class="nav-link" href="#">Music</a></li>
            <li class="facebook"><a href="#"><i class="fab fa-facebook fa-2x"></i></a></li>
              <li class="twitter"><a href="#"><i class="fab fa-twitter fa-2x"></i></a></li>
              <li class="instagram"><a href="#"><i class="fab fa-instagram fa-2x"></i></a></li>
          </ul>
  </div>
  </nav>

https://codepen.io/pgurav/pen/abbQZJL

Answer №5

I've put together a sample for you, drawing from the bs4 documentation on external content handling.

<div class="pos-f-t">
  <div class="collapse" id="navbarToggleExternalContent">
    <div class="bg-dark p-4">
      <h5 class="text-white h4">Collapsed content</h5>
      <span class="text-muted">Toggleable via the navbar brand.</span>
    </div>
  </div>
  <nav class="navbar navbar-dark bg-dark navbar-expand-lg">
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
  </nav>
</div>

In this example, the code collapses from the top rather than the right. I'm currently away but will work on tweaking the example to better suit your requirements when I return.

Some extra JavaScript:

var externalContent = $('#navbarToggleExternalContent'),
    execOnResize = function(){
// this line was specific to jsfiddle only
// in actual use, utilize window.outerWidth instead
// 992 pixels represent the breakpoint width for the "navbar-expand-lg" class. Adjust as needed.
    if(window.innerWidth >= 992){
        externalContent.addClass('show');
    }else{
        externalContent.removeClass('show');
    }
};
// this line was added for jsfiddle purposes only       
execOnResize();

window.onresize = function(event) {
    execOnResize();
};

window.addEventListener('load', function() {
    execOnResize();
})

I've also prepared a fiddle here. You can witness it in action by adjusting the inner window size within the jsfiddle.

Answer №6

To ensure that your JavaScript code runs effectively based on the device being used, it is important to implement logic that can differentiate between computers and mobile phones.

One approach is to leverage the browser's UserAgent:

$('.menu-close').on('click', function(){
    if(navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {
        //mobile
        $('#menuToggle').toggleClass('active');
        $('body').toggleClass('body-push-toright');
        $('#theMenu').toggleClass('menu-open');
        alert("Test");
    }
});

Alternatively, you could opt to assess the window's width (bearing in mind that smaller desktop windows may be categorized as mobile):

if(window.innerWidth <= 767) { // a certain threshold value, in pixels
    //mobile
    //perform specific actions
}

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

Create a border surrounding the matColumn within a sticky matTable

I am currently working with a matTable that has the first two or three columns set as sticky. However, I am facing an issue where the scrolling behavior of the non-sticky columns under the sticky ones looks like a glitch due to existing border styling on t ...

Disregard the significance of radio buttons - iCheck

I have been attempting to retrieve values from radio buttons (using iCheck), but I am consistently only getting the value from the first radio button, while ignoring the rest. Despite following what seems to be correct code theory, the output is not as exp ...

Looking to tidy up the HTML produced by JQueryUI?

Is there a way to achieve this? I am developing a template generator that includes resizable and draggable elements within a preview window. The issue arises when I try to extract the generated HTML, as it contains unwanted JQueryUI classes and divs for ea ...

Create a new modal design by keeping the structure but updating the text and images for

Is there a way to simplify the process of creating multiple modals on my website without having to duplicate and adjust the code each time? I would appreciate any assistance in achieving this! I have a specific modal template that I want to replicate, wit ...

Material UI button text not receiving props

Within my application, I have a situation where I utilize data attributes on buttons to gather specific contextual information in the modal that is triggered by clicking the button. This functionality depends on accessing the data attributes through e.targ ...

Is there a way to prevent the "undefined" message from displaying in the console when this code is run?

Help needed! Can someone assist me in resolving the issue where the word 'undefined' is being displayed in the console? I'm a beginner in programming and struggling with this. Here's what I'm currently seeing: You are not getti ...

React Native Issue: The mysterious disappearance of the 'navigation.push' object

I am trying to navigate to List.js after clicking a button in the MainMenu.js file, but I keep encountering this error: TypeError: undefined is not an object (evaluating 'navigation.push') This snippet is from my App.js file import { StatusBar ...

Using jsPlumb to Access an Element After a "Mouseup" Event has Completed

$(document).on('mouseup', '.agent-wrapper', function(info){ console.log(info); // Everything is working fine console.log(this); }); .agent-wrapper represents an element-wrapper for all jsPlumb objects. $(document).on(' ...

"Create a React button component that, when clicked, navig

I'm currently developing a web application using React and bootstrap. I'm facing difficulties in redirecting the page to another one when applying onClick to buttons. After adding a href, I'm unable to navigate to another page. Do you think ...

Adding a see-through Bootstrap Navbar to a Fullpage.js website: A step-by-step guide

I am trying to incorporate a transparent Bootstrap Navbar into my page that is using fullpage.js. The desired outcome is for the navbar to stay on top of the page without affecting the layout of the website content. I have referenced an example here, but ...

Encountered a POST Error while attempting to access a backend function from the frontend in a React application, resulting in

I have developed a website using React for the frontend and Node.js Express for the backend. However, I am facing an issue where calling a backend function from the frontend takes around 2 minutes and results in the following error being displayed in the c ...

An issue arose in Leaflet where drawing on the map became impossible after making an update to a marker's position

I have been working with Leaflet, Leaflet-draw, and Cordova Geolocation. Initially, when the map is loaded in globe view, drawing works perfectly. However, when the locate function is called to update the map center and marker position, drawing becomes imp ...

Tips for resizing the MUI-card on a smaller screen

Is there a way to adjust the width of the card on small screen sizes? It appears too small. You can view my recreation on codesandbox here: https://codesandbox.io/s/nameless-darkness-d8tsq9?file=/demo.js The width seems inadequate for this particular scr ...

What is the process for transforming a method into a computed property?

Good day, I created a calendar and now I am attempting to showcase events from a JSON file. I understand that in order to display a list with certain conditions, I need to utilize a computed property. However, I am facing difficulties passing parameters to ...

What is the best way to add a blob to the document object model (

I am a beginner when it comes to working with blobs, and I am looking for some guidance to avoid wasting hours on unsuccessful brute-force attempts. I have been using the PHP code below (sourced from here) to retrieve the base64-encoded image from my data ...

Implementing bootstrap columns while displaying individual components one after the other

Here is the html code I am currently working with: <label>Search:</label> <input type="text" id="list_search" class="form-control col-8"> <button class="btn btn-info col-2">Search</button> It's interesting to note that ...

Use PHP to open a text file and display its contents in a textarea

I have a textarea on my website and I'm trying to figure out how to populate it with the content of a text file. I followed a tutorial that guided me through writing some code, but when I implement it, I'm facing an issue where the words from the ...

What is the best way to implement CSS Float in typescript programming?

For a specific purpose, I am passing CSS Float as props. To achieve this, I have to define it in the following way: type Props = { float: ???? } const Component = ({ float }: Props) => {......} What is the most effective approach to accomplish this? ...

Is there a way to automate the uploading of captcha images to this solving service using Python?

Currently, I am working on a Python program with the goal of solving captchas on a website. My plan is to integrate 2captcha into the solution. Using Selenium, I have managed to write a Python script that fulfills all required tasks except for solving the ...

AmplifyJS is throwing an error: TypeError - It seems like the property 'state' is undefined and cannot be read

I am currently working on integrating the steps outlined in the Amplify walkthrough with an Angular cli application. My app is a brand new Angular cli project following the mentioned guide. My objective is to utilize the standalone auth components a ...