Responsive navbar in Bootstrap collapses and closes again after opening on a small screen

Although the navbar functions properly on larger screens, it collapses back after pressing the collapse icon when viewed on a mobile screen.

<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>

<body style="background-color: #7e9094;">
  <nav style="background-color: #213239;" class="navbar navbar-expand-lg navbar-dark">
    <a class="navbar-brand active" href="index.html">Home</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
    
    <div class="collapse navbar-collapse" data-target="#demo" id="navbarText">
      <ul class="navbar-nav" id="demo">
        <li class="nav-item">
          <a class="nav-link" href="shop/shop.html">Shop</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="projects/projects.html">Projects</a>
        </li>
      </ul>
      <span class="navbar-text"><a class="nav-link" href="index.html"><img style="float: right;" width="10%" src="img/image.img"></a></span>
    </div>
  </nav>
</body>

</html>

Answer №1

To ensure your JavaScript and CSS versions match, update the CDN link for your JavaScript to 4.x as well.

<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.min.js"></script>
</head>;

<body style="background-color: #7e9094;">
  <nav style="background-color: #213239;" class="navbar navbar-expand-lg navbar-dark">
    <a class="navbar-brand active" href="index.html">Home</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button>
    
    <div class="collapse navbar-collapse" data-target="#demo" id="navbarText">
      <ul class="navbar-nav" id="demo">
        <li class="nav-item">
          <a class="nav-link" href="shop/shop.html">Shop</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="projects/projects.html">Projects</a>
        </li>
      </ul>
      <span class="navbar-text"><a class="nav-link" href="index.html"><img style="float: right;" width="10%" src="img/image.img"></a></span>
    </div>
  </nav>
</body>

</html>

Answer №2

Just to add onto the responses from @isherwood and @MrUpsidown.

Your code has mismatched css, jquery, and bootstrap versions.

If you're aiming to use Bootstrap's latest version, ensure your css matches the version (currently 4.3.1) and consider using the slim build of jquery. You can find more information in the 'Getting started' guide for Bootstrap 4.3.

Alternatively, if you actually need Bootstrap 3.4.1, make sure to align your css and jquery accordingly as detailed in the 'Getting started' guide for Bootstrap 3.4. For an example navbar structure, check here.

In such a scenario, your code would resemble:

<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
        integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body style="background-color: #7e9094;">
    <nav style="background-color: #213239;" class="navbar navbar-expand-lg navbar-default">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbarText"
                aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Home</a>
        </div>
        <div class="collapse navbar-collapse" data-target="#demo" id="navbarText">
            <ul class="navbar-nav" id="demo">
                <li class="nav-item">
                    <a class="nav-link" href="shop/shop.html">Shop</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="projects/projects.html">Projects</a>
                </li>
            </ul>
            <span class="navbar-text">
                <a class="nav-link" href="index.html"><img style="float: right;" width="10%" src="img/image.img"></a>

            </span>
        </div>
    </nav>
</body>

</html>

Remember that 3.4.1 and 4.3.1 are distinct versions. Best of luck!

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

Empty space to the left of the vertical navigation bar

I'm struggling to get rid of the white space on the left side of my vertical navigation bar. I've attempted setting padding-left to 0 on my main navigation bar. This is my first time creating a navigation bar, so if you notice any semantic issu ...

Incorporating rounded corners to an embedded YouTube video

Check out this JSFiddle link. The border-radius property appears to be working correctly at first, but then the rounded corners suddenly disappear shortly after loading. Is there a way to apply rounded corners to YouTube videos that are embedded on a webp ...

methods for transferring javascript variables to modal

<div> <h5> <a href="<?php echo base_url(); ?>/vendor/home/projects" >Return to Projects</a> </h5> <div> <div class="container"> <div class="row"> ...

Tips on obtaining a byte array from within a JSON object

I am currently facing a challenge in retrieving a PDF file from the server, which is enclosed within a JSON object. When I send a byte array of the PDF to the front-end, I can successfully read it by configuring the responseType to arraybuffer. Subsequent ...

I am experiencing an issue where my AngularJS CORS request is not reaching the server

Recently, I encountered a problem with my Spring MVC API backend where CORS was correctly configured. However, when attempting to make an Ajax call, Chrome threw the following error: XMLHttpRequest cannot load 172.20.16.45:8082/cuponza. The request was ...

Troubleshooting Problems with Positioning and Floating in HTML and CSS

I'm facing some challenges with clearing floats (or it could be something else?). My goal is to have the #newsbar div free from the previous floats so that its width can extend 100% across the page/browser. I believe I've tried everything within ...

Exploring an object to retrieve values based on keys using javascript

Currently, I have an array of objects set up like this: https://i.sstatic.net/l6d3z.png My goal is to loop through the array and extract users based on a specific roomCode So, I've attempted two different approaches: for(let i=0; i <data. ...

Utilizing dynamic content to pass arguments to JavaScript functions

I'm facing a challenging issue that is causing me frustration. While browsing through this platform, I found some potential solutions but encountered a roadblock in implementing them successfully. My current project involves developing an e-commerce p ...

Instructions for creating a directional route on a map using highcharts

I am currently working on implementing highcharts maps with flight routes, similar to the visualization shown in this Highchart-maps with flight routes example. My goal is to display the routes in a way that resembles the output illustrated in this expecte ...

When trying to parse a non-alphanumeric string using Number.parseInt, the resulting type will be 'number'

Here's what is going on: The typeof Number.parseInt('processed') statement returns 'number'. https://i.sstatic.net/1mpaI.png However, when Number.parseInt('processed') results in NaN. https://i.sstatic.net/gVVgV.png ...

Importing a form input as a constant in an API endpoint script

Recently stepping into the realm of React, I'm encountering difficulties in my Next.js app related to imports and exports. My goal is to export a const from a form component to an API endpoint for use within a function. While I can see the form compo ...

Exploring Angular's Implementation of D3 Force Simulation

Looking to incorporate a d3 force simulation in my Angular app. I have a run method that initializes and sets simulation options, as well as a ticked method that updates the simulation on each tick. However, I've encountered a few problems with this s ...

Utilize ZLIB and Node.js to create a compressed zip archive of a folder's contents

I need to compress all the files in a directory into a single ZIP file. Currently, I am using this code snippet: var fs = require('fs'); var tar = require('tar'); var zlib = require('zlib'); var path = require('path&apo ...

The Nodejs express static directory is failing to serve certain files

Hello everyone, I'm currently working on a project using NodeJs, Express, and AngularJS. I've encountered an issue where my page is unable to locate certain JavaScript and CSS files in the public static folder, resulting in a 404 error. Strangely ...

manipulating the flow of callback functions using jQuery

When the function socialbookmarksTableData(data) is called by another function, it generates the content of a table using data in JSON format. Inside this function, two other functions are called which use getJSON and POST methods to retrieve some data. ...

Accordion featuring collapsible sections

Looking to build an accordion box using Javascript and CSS. The expanded section should have a clickable link that allows it to expand even further without any need for a vertical scroll bar. Any ideas on how this can be achieved? Thank you ...

Error encountered in ASP page due to JavaScript syntax issue

<script type="text/javascript"> /* <![CDATA[ */ var on_id = 1; if (<%=GetValue() %>) { on_id = <%=GetValue() %>; } </script> I am encountering two syntax errors: one ...

Struggling to extract information from a serialized Python object using JavaScript/jQuery?

Continuing the previous issue with an AJAX call to a Django view (restframework endpoint), the problem has now shifted to the frontend. $.ajax({ url: '/notify/', type:'GET', dataType: '', success: function (da ...

The Django development server seems to be having trouble serving up Bootstrap 3 glyphicons

I'm facing an issue with a glyphicon from bootstrap in one of my templates on my website. Whenever I try to access the page, a 404 error pops up in the terminal and the icon doesn't appear. What's confusing is that the page works fine as a s ...

Unable to function properly on Backbone.js, events have been rendered ineffective

I have recently created a view with the following code snippets: var app = app || {}; app.singleFlowerView = Backbone.View.extend({ tagName: 'article', className: 'flowerListItem', // specifies where to render the views templ ...