The jQuery navbar's active class fails to function properly when an href is added

I'm facing a puzzling situation. I created a navbar using jQuery Mobile following the instructions on their official website: jQuery Mobile Navbar Demos

Everything functions smoothly until I introduce href attributes in the list elements within the unordered list (the selected items in the navbar fail to activate):

<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div id="menu">
  <div data-role="navbar">
    <ul>
      <li><a href="" class="contentUpdate" id="1"><i class="fas fa-swimmer"></i>Swim</a></li>
      <li><a href="" class="contentUpdate" id="2"><i class="fas fa-biking"></i>Cycle</a></li>
      <li><a href="" class="contentUpdate" id="3"><i class="fas fa-running"></i>Run</a></li>
    </ul>
  </div>
  <!-- /navbar -->

</div>

When I modify the href attribute to link to another div (for a webpage where clicking the navbar item changes content), the active class fails to trigger when clicked.

<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div id="menu">
  <div data-role="navbar">
    <ul>
      <li><a href="#swim" class="contentUpdate" id="1"><i class="fas fa-swimmer"></i>Swim</a></li>
      <li><a href="#cycle" class="contentUpdate" id="2"><i class="fas fa-biking"></i>Cycle</a></li>
      <li><a href="#run" class="contentUpdate" id="3"><i class="fas fa-running"></i>Run</a></li>
    </ul>
  </div>
  <!-- /navbar -->
</div>

I attempted adding a class to the items with jQuery, but it did not produce the desired outcome. When I implement the following code, only the first item fails to become active upon clicking:

$("#1").click(function() {
  $("#1").addClass("ui-btn-active");
});
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div id="menu">
  <div data-role="navbar">
    <ul>
      <li><a href="#swim" class="contentUpdate" id="1"><i class="fas fa-swimmer"></i>Swim</a></li>
      <li><a href="#cycle" class="contentUpdate" id="2"><i class="fas fa-biking"></i>Cycle</a></li>
      <li><a href="#run" class="contentUpdate" id="3"><i class="fas fa-running"></i>Run</a></li>
    </ul>
  </div>
  <!-- /navbar -->
</div>

However, the scenario changes when I apply the code below as the remaining two items successfully transition to the active state:

$("#1").click(function() {

  $("#1").addClass("ui-btn-active");
  $("#2").addClass("ui-btn-active");
  $("#3").addClass("ui-btn-active");

});
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<div id="menu">
  <div data-role="navbar">
    <ul>
      <li><a href="#swim" class="contentUpdate" id="1"><i class="fas fa-swimmer"></i>Swim</a></li>
      <li><a href="#cycle" class="contentUpdate" id="2"><i class="fas fa-biking"></i>Cycle</a></li>
      <li><a href="#run" class="contentUpdate" id="3"><i class="fas fa-running"></i>Run</a></li>
    </ul>
  </div>
  <!-- /navbar -->
</div>

I am perplexed by this behavior. If anyone has insights or suggestions, I would greatly appreciate your help. Here's an example of My Navbar with an active class.

Answer №1

Merely checking the navbar anchor click is not sufficient. For a solution that also functions with the back-button, or when navigating in code, after transitions, and with an external toolbar, you will need to verify the current page inside the pagecontainerchange trigger and update the navbar accordingly:

$(function(){
  $( "[data-role='header'], [data-role='footer']" ).toolbar({ theme: "a" }).enhanceWithin();
});

$( document ).on( "pagecontainerchange", function(e, ui) {
  if(typeof ui.toPage == "object") {
    var id = $.mobile.activePage.attr("id"),
      navbar = $("[data-role=navbar]"),
      buttons = navbar.find(".ui-btn"),
      current = navbar.find("a[href='#"+id+"']");
    buttons.removeClass($.mobile.activeBtnClass);
    current.addClass($.mobile.activeBtnClass);
  }
});
<!DOCTYPE html>
<html>
  <head>
    <title>Focus Tab</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
    <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css" />
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.js"></script>
  </head>
  <body>
    <div data-role="header">
      <div id="menu" data-role="navbar">
        <ul>
          <li><a href="#swim" id="1">Swim</a></li>
          <li><a href="#cycle" id="2">Cycle</a></li>
          <li><a href="#run" id="3">Run</a></li>
        </ul>
      </div>
    </div>
    <div id="swim" data-role="page">
      <div data-role="content">Page Swim </div>
    </div>
    <div id="cycle" data-role="page">
      <div data-role="header" data-add-back-btn="true">
        <h3>My app</h3>
      </div>
      <div data-role="content">Page cycle</div>
    </div>
    <div id="run" data-role="page">
      <div data-role="content">Page run</div>
    </div>
  </body>
</html>

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

Calculating the total amount by combining the quantity and price fields in

I currently have multiple tables generated dynamically using PHP <table class="table11"> <tbody> <tr> <td>Name</td> <td class="quantity">2</td> <td class="price">20</td> & ...

Including new styles in CKEDITOR.stylesSet that pertain to multiple elements

My idea involves creating a unique bullet list style with two specific features: a. A blue arrow image replacing the standard list icon b. Very subtle dotted borders above and below each list item. I am looking to incorporate this design into CKEditor t ...

What is the method for creating a line break in text?

Here is some example code I have: <h3 class="ms-standardheader"> <nobr> Reasons for proposals selected and not selected </nobr> </h3> Now I also have an image to show. The problem is that my text appears too large, so I a ...

Adjustable DIV based on screen size

I am attempting to create a flexible div that will adjust its width and height proportionally based on the viewport size. However, in the example above, this method only seems to make the div expand horizontally without affecting the vertical height (wh ...

Struggling to locate an element with jQuery's closest() method?

Currently, I am utilizing jQuery and Ruby on Rails for my project. Within a table with 3 columns, there is a form element in the form of a select box that utilizes AJAX to submit the result. My goal is to change the color of a check mark by adding or remov ...

Creating a dynamic onclick function that depends on a variable passed from a while loop in PHP

If you're familiar with PHP, I have a scenario for you. Let's say there's a list of items generated using a while loop in PHP. Each item has a sub-list that should only appear when clicked on. I tried using the onclick function in jQuery but ...

How can I switch between different images using jQuery?

HTML <div class="image_rollover"> <img id="image_one" src=image_one.png"> <img id="image_two" src="image_two.png"> <img id="image_three" src="image_three.png"> <img id="image_four" src="image_four.png"> ...

The AJAX request contains additional parameters in the URL, such as http://localhost:1964/a/b?_=1830

Can someone explain why the URL changes to /a/b?_=1830 and returns a 500 (Internal Server Error)? $.ajax({ url:'/a/b', type: 'GET', cache: false, async: false, dataType: 'JSON', ...

Retrieving attribute values when using the .on function in jQuery

I currently have 10 links with the following format: <a href="#" data-test="test" class="testclass"></a> as well as a function that looks like this: $(document).on("click", ".testclass", function () { alert($(this).attr('data-t ...

What is the best way to use an Infinite scroll plugin to automatically fetch additional data from a database as the user scrolls down

In my Laravel Blade View, I am showcasing around 280 products from the database using the code snippet below. @if (get_setting('best_selling') == 1) <section class="mb-4"> <div class="container"> ...

Is there a way for me to implement this code to achieve the functionality shown in the demo link

$('select').change(function() { var sum = 0; var sum = parseInt($('select[name="bathrooms"]').val() * 25) + parseInt($('select[name="bedrooms"]').val() * 8); $("#sum").html(sum); }); <script src="https://ajax.googleap ...

successful ajax call encountered a problem

Here is the code snippet in question: $.ajax({ type: "POST", url: "/Member/SaveMember", data: $('form').serialize(), success: refreshGrid() I'm confused as to why the refreshGrid() method is being called before the ajax call to /Member/Sav ...

How can I make a DIV occupy the entire vertical space of the page?

I am working on a Google Maps application that takes up the majority of the screen. However, I need to reserve a strip at the top for a menu bar. How can I ensure that the map div fills the remaining vertical space without being pushed past the bottom of ...

jQuery does not permanently alter the values

It is unclear whether this issue is related to caching or coding. Interestingly, there seems to be inconsistency when attempting to modify the value of a div using text(); it works at times and fails at other times... EDIT SOLVED SEE BELOW: The problem wa ...

The resize function fails to trigger when it is required

Struggling to get this code working properly. If the window width is greater than 800, I want 6 images with a red background. If the window width is less than 800, I want 4 images with a blue background. I need this functionality to work both on r ...

Troubleshooting a Problem with AngularJS $.ajax

Oops! Looks like there's an issue with the XMLHttpRequest. The URL is returning a preflight error with HTTP status code 404. I encountered this error message. Any thoughts on how to resolve it? var settings = { "async": true, "crossDomain": ...

CKEditor's height automatically increases as the user types

I am using a ckEditor and looking for a way to make its height automatically grow as I type. https://i.stack.imgur.com/m7eyi.png <textarea name="description" id="description"> </textarea> <script> CKEDITOR.replace( 'description ...

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

Converting lists to JSON format in a C# web form

Utilizing JSON.stringify, I have implemented textbox autocomplete for a web-form that suggests city names based on user input. The goal is to retrieve relevant city names from the database and display them as suggestions in the autocomplete feature after t ...

Sending emails to multiple groups in Opencart can be easily achieved with the

I am interested in customizing Opencart's admin panel to allow for the selection of multiple customer groups when sending emails. However, I am unsure of where and how to make these modifications as I am relatively new to this type of task. ...