`After the initial instance, the menu title will be altered.`

I have a responsive menu using Bootstrap. When the menu is collapsed, I want it to display the name of the page, and when it is open, I want it to show "Menu."

Currently, I have named it "Watch the Trailer" (so let's assume that we are on that page). When I click the button, the title changes, but it only works correctly after the first click. Why is this happening?

Is my approach the best way to achieve this? You can view the code on jsfiddle for convenience.

var menu_title = $(".so_menu_name").html();
    
$(".navbar button").on("click", function () {
  var collapsed = $(".navbar button").hasClass("collapsed");
  if (!collapsed) {
    $(".so_menu_name").html(menu_title);
  }
  else {
    $(".so_menu_name").html("Menu");
  }
});
.nav.navbar-nav .nav-item {
      float: none;
}

.nav.navbar-nav .nav-item+.nav-item {
      margin-left: 0;
}
.nav.navbar-nav .nav-link {
      padding: .25rem 0;
}
.nav.os_menu {
      border-top: 2px solid rgba(255, 255, 255, .5);
      border-bottom: 2px solid rgba(255, 255, 255, .5);
}
<div class="container">

  <nav class="navbar navbar-dark bg-inverse">
    <span class="so_menu_name">Watch the Trailer</span>
    <button class="navbar-toggler hidden-sm-up" type="button" data-toggle="collapse" data-target="#collapsingNavbar">+</button>

    <div class="collapse navbar-toggleable-xs" id="collapsingNavbar">

      <ul class="nav navbar-nav os_menu">
        <li class="nav-item active">
          <a class="nav-link" href="#">Watch the Trailer<span class="sr-only">(current)</span></a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Screening & Events</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Synopsis</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">The Protagonist</a>
        </li>
      </ul>

    </div>
  </nav>

</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №1

In my analysis of the plugin, I have identified some issues. The class called collapse is not added or removed during the first click.

To resolve this issue, you can utilize the attribute aria-expanded.

var menu_title = $(".so_menu_name").html();

$(".navbar button").on("click", function () {
//  var collapsed = $(".navbar button").hasClass("collapsed");
if ($(this).attr('aria-expanded') == "true") {
  $(".so_menu_name").html(menu_title);
}
else {
  $(".so_menu_name").html("Menu");
}

});

Test it on fiddle.

Answer №2

Check out this link for a demonstration: DEMO

I included some additional text within the button element.

<button class="navbar-toggler hidden-sm-up" type="button" data-toggle="collapse" data-target="#collapsingNavbar">
   View the Trailer +
  </button>

Answer №3

Here is my suggestion:

The following are the key modifications:

<div class="navbar-toggleable-xs collapse in" id="collapsingNavbar">

as well as:

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsingNavbar">
    <span class="so_menu_name">Watch the Trailer</span>
</button>

$(function () {
  var menu_title = $(".so_menu_name").html();

  $("button.navbar-toggler").on("click", function (e) {
    e.preventDefault();
    var collapsed = $(this).hasClass("collapsed");
    if (collapsed) {
      $(".so_menu_name").text(menu_title);
    }
    else {
      $(".so_menu_name").text("Menu");
    }
  });
});
.nav.navbar-nav .nav-item {
  float: none;
}
.nav.navbar-nav .nav-item+.nav-item {
  margin-left: 0;
}
.nav.navbar-nav .nav-link {
  padding: .25rem 0;
}
.nav.os_menu {
  border-top: 2px solid rgba(255,255,255,.5);
  border-bottom: 2px solid rgba(255,255,255,.5);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js"></script>


<div class="container">
    <nav class="navbar navbar-dark bg-inverse">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsingNavbar">
            <span class="so_menu_name">Watch the Trailer</span>
        </button>
        <div class="navbar-toggleable-xs collapse in" id="collapsingNavbar">
            <ul class="nav navbar-nav os_menu">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Watch the Trailer<span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Screening & Events</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Synopsis</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">The Protagonist</a>
                </li>
            </ul>
        </div>
    </nav>
</div>

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

The jQuery Ajax call encountered an error when trying to make a GET request to a different

My goal is to make a request to a different domain using the following URL: http://ccv.viatelecom.com/services/?item=viacall&aid=XXXX&gid=XXXX&sid=XXXX&&num=XXXXXX To achieve this, I have implemented an Ajax request like so: $.ajax({ ...

Error is being returned by the JSONP callback

Looking to grasp JSONP. Based on my online research, I've gathered that it involves invoking a function with a callback. Other than that, is the way data is handled and the data format similar to JSON? I'm experimenting with JSONP as shown below ...

Page redirects automatically after AJAX call

I'm a beginner when it comes to using AJAX and I am trying to delete a student from a list through an AJAX request. I want the response of the request to be displayed on the same page within a specific div, but instead, the response keeps redirecting ...

Function activation in Element requires a double click to initiate

I've encountered an issue with a web element I'm working on where the click function only triggers after the first click, rendering the initial click ineffective. Here's the code snippet in question: HTML: <div> <a href="#0" cla ...

Navigate quickly to different sections using jump links and adjust the positioning with the style attribute, such as "padding-top

My website incorporates Jump Links to navigate between page elements as part of an interactive User Guide. Everything functions properly on Firefox, IE, and Edge, but Chrome and Opera seem to disregard the 'padding'. Due to a fixed menu bar on t ...

Customize dropdown item colors in React using a color picker

I am currently utilizing a react color picker to create a personalized 16 color gradient. The process involves selecting a color from a dropdown menu and then using the color picker to make adjustments. This action updates an array that dictates the stylin ...

The boundary of embedded components

I am looking for CSS code that will allow me to arrange all elements with specific indents, such as placing the first element on the left side of the page, followed by an image with some indentation, and so on. <div class="container-fluid"> &l ...

Ways to have a dropdown menu automatically close when opening another dropdown

Having an issue with managing multiple href links on a single page. When one link is clicked, it opens a dropdown, but if another link is clicked without closing the first one, the first dropdown remains open. How can I resolve this? I initially attempted ...

Issue with calculating positions in the jquery.quicksand plugin

I've been playing around with a website for the past couple of days and I have successfully implemented the jquery.quicksand plugin to organize my portfolio entries. However, I've run into an issue when selecting the 'all' filter. If a ...

Position a div at the bottom of another div using Bootstrap

I'm facing an issue with trying to position an inner div at the bottom of an outer div using bootstrap classes. I have attempted various methods in both bootstrap and regular CSS, such as vertical-align: bottom; and setting position to absolute, but n ...

Executing the JavaScript function on a batch of 6 IDs at once (should return every 6 calls?)

I'm curious if there's a function available that can group called data into sets of 6. Here's the expanded version of the code var currentResults; function init() { getProducts(); } function getProducts() { $.ajax({ url:" ...

Manipulating div positions using JQuery and CSS

Whenever I hover over the #HoverMe div, a hidden #hidden div appears, and when I unhover it, the hidden div disappears again. The #hidden div contains a sub-div that functions like a dropdown list. The #hidden div is styled with position: absolute;. How ca ...

The CSS classes for the dropzonejs are not being properly updated for editing purposes

I'm currently facing an issue where I am attempting to include an editable area inside a dropzone, but for some reason, the editable area is not visible within the dropzone and the CSS classes are not being applied. <a href="#" editable-text="us ...

Navigating through a table using jQuery to find a specific element

There are form input elements within an HTML table structured like this: <table> <thead> .... </thead> <tr> <td><input type="text" name="n_time" id="5030c9261eca0" value="2012" /></td> ...

Update the content of a div and refresh it when a key on the keyboard is pressed

I need to hide the images in a div when I press a key on the keyboard. How can I achieve this? <div> <span role="checkbox" aria-checked="true" tabindex="0"> <img src="checked.gif" role="presentation" alt="" /> ...

The presence of certain characters is leading to problems in the console

Similar Question: Escaping a String for JavaScript Usage in PHP? The characters in my text are causing errors. When I input special characters such as: !\"$%^&()-=\'.,:;/?#~/\\>< An error saying "Syntax error ...

"Troubleshooting the issue of consistently receiving null values when uploading files with

I'm facing an issue with uploading a file using jQuery AJAX. Although I can see all the details of the file object such as its name and size, when I check the console with formdata.get("files"), the context.request.files size always shows zero. It see ...

What could be the reason that my for loop executes only when it is embedded within a while loop?

Hey there, I've been trying to understand why this code snippet works when the while loop is included: some = 0 n = 5 while some == 0: for title in itertools.islice(driver.find_elements_by_css_selector("a[class='link-title']"), ...

Firefox does not support CSS transitions

I've put in a lot of effort and even tried searching on Google, but I'm unable to find a solution to my problem: To help you understand my issue better, I have created a jsfiddle with my source code: Click here to view my Source Code Although e ...

Updating the source of an iframe when the linked file is modified or updated

Currently, I am in the process of developing a page named live_link_frame.php. This page includes loading an iframe through a URL retrieved from a local file called live_link.txt: <?php $filePath = 'live_link.txt'; $handle = @fopen($filePath, ...