The burger icon for toggling the navigation bar on the template does not seem to be functioning properly on

Unable to toggle hamburger icon on mobile view using Rails...

I'm experiencing an issue with the navbar button in Rails that was obtained from a template. The navbar button toggles correctly and registers a click event which is logged in the console.

The template works fine in a browser, but when implemented in Rails, it fails to work. I have added the code to the main app.js file to rule out any asset pipeline issues, considering the original js file from the template is lengthy (30k lines).

I've experimented with enabling and disabling turbolinks. A console log indicates that jQuery is reactive to the click event, yet the navbar remains unresponsive, suggesting the code is being accessed properly. Debugging the JavaScript in Chrome was inconclusive as the click event seemed to be bouncing around various parent and child elements during debugging.


//
//= require jquery
//= require jquery_ujs
//= require rails-ujs
//= require page
//= require script
//= require popper
//= require bootstrap
//= require activestorage
//= require_tree .

 /**
  * page is the main js file, loaded from vendor/assets
 */

$(document).on('ready turbolinks:load', function() {
    page.initNavbar = function() {

        /**
         * Toggle navbar
         */
        $(document).on('click', '.navbar-toggler', function() {
          page.navbarToggle();
          console.log("navbar clicked")
        });

        /**
         * Tapping on the backdrop will close the navbar
         */
        $(document).on('click', '.backdrop-navbar', function() {
          page.navbarClose();
        });

        /**
         * Toggle menu open on small screen devices
         */
        $(document).on('click', '.navbar-open .nav-navbar > .nav-item > .nav-link', function() {
          $(this).closest('.nav-item').siblings('.nav-item').find('> .nav:visible').slideUp(333, 'linear');
          $(this).next('.nav').slideToggle(333, 'linear');
        });

      }

      page.navbarToggle = function() {
        var body   = page.body,
            navbar = page.navbar;

        body.toggleClass('navbar-open');
        if (body.hasClass('navbar-open')) {
          navbar.prepend('<div class="backdrop backdrop-navbar"></div>');
        }
      }

      page.navbarClose = function() {
        page.body.removeClass('navbar-open');
        $('.backdrop-navbar').remove();
      }

});

The erb

<nav class="navbar navbar-expand-lg navbar-light navbar-stick-dark" data-navbar="smart">
      <div class="container">
        <div class="navbar-left mr-4">
          <button class="navbar-toggler" type="button">&#9776;</button>
          <a class="navbar-brand" href="#">
          <%= link_to root_url do %>
           <% if controller_name == "home" %>
            <%= image_tag 'uproar-light.png', class: 'navbar-brand'%>
            <% else %>
            <%= image_tag 'uproar-dark.png', class: 'navbar-brand'%>
              <% end %>
            <% end %>
          </a>
        </div>

        <section class="navbar-mobile">
          <nav class="nav nav-navbar mr-auto">
            <a class="nav-link active" href="#home">Home</a>
            <a class="nav-link" href="#section-features">Features</a>
            <a class="nav-link" href="#section-pricing">Pricing</a>
            <a class="nav-link" href="#">Resources</a>
            <a class="nav-link" href="#">Contact</a>
          </nav>

          <div class="d-none d-stick-block">
            <a class="btn btn-sm btn-light ml-lg-5 mr-2" href="#">Login</a>
            <a class="btn btn-sm btn-success" href="#">Sign up</a>
          </div>
        </section>

      </div>
    </nav>

Answer №1

Finally cracked the code on getting the navbar toggle to function properly after quite a bit of trial and error. By placing the javascript include tags in the footer, I was able to make it work seamlessly.

It turns out that the JavaScript from the theme needed to load last to be effective. This is a common occurrence outside of Rails, but I discovered a workaround to load the JavaScript asynchronously without interfering with turbolinks.

<%= javascript_include_tag "application", async: true %>

Simply adding async: true to each javascript tag resolved the issue, and now the toggle functionality works flawlessly. I then moved the include tags back to the header for organization.

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

Could we filter and retrieve only one unique notificationType/postId combination?

I have a notification model with the following Schema definition: const NotificationSchema = new Schema({ type: { type: String, required: true }, createdAt: { type: Number, required: true }, postId: { type: Schema.Types.Objec ...

Revealing elements with AngularJS ng-show directive prior to concealing them

Currently, I am in the process of implementing a slide effect for bootstrap badges to showcase hierarchical data relationships using AngularJS. My goal is to have a slider-effect that smoothly reveals new sub-categories while concealing previously open su ...

Anticipated semicolon in the JavaScript file

I recently came across the dialogflow demo as a reference. However, I encountered an error stating 'semicolon expected' at the method sendTextMessageToDialogFlow. How can I resolve this issue? Below is the code snippet: router.post('/dialo ...

What are the drawbacks of utilizing the onClick function in JavaScript?

What is the rationale behind programmers opting not to use onClick function in Javascript? ...

Preserve the output from the jQuery ajax request

I have created a custom function that calls an ajax request and saves the response data to a variable before returning it. It always shows '0' as the return value, but the alert displays numbers like 3712. Below is the implementation of the func ...

The Android WebView is unable to run JavaScript code in a local HTML file

Currently, I am attempting to load a local HTML file from the assets folder into a webview. Even though I can successfully load the HTML file in the webview, there seems to be an issue with the file's reliance on an external .js file for calculations. ...

Tips for arranging HTML elements in a horizontal line, even if they belong to different parent elements

My HTML document features a sticky header and footer, with a div below the header that sticks to it to eventually hold tabs above a form. I've been struggling to align the form vertically below this div. The issue arises because the tab div lacks a sc ...

Typography Addition on Flexslider

I am currently working with flexslider and trying to incorporate a unique text overlay on each individual slide, but so far I have been unsuccessful. <div class="flexslider"> <ul class="slides"> <li> <img src ...

How to extract value from the URL in NextJS

I am attempting to pass a value through the URL and then extract that value in search.js using a router. However, I keep encountering this error: TypeError: Cannot read properties of undefined (reading 'q') <form onSubmit={handleSubmit}&g ...

The text geometry remains consistent despite adjustments to the height and size parameters

I am facing a unique issue with text loading in my react three fiber project. The text does render, but it remains extremely small and unreadable, even though I can see a tiny pixel of the text color in the correct position. Strangely, I have not been able ...

Creating a Consistent Look for Italic Font Formatting in Tailwind

In an effort to establish consistent typography on a website being developed by my team, we have devised custom utility classes in Tailwind. One of these classes, small-italicized, also requires the text to be italicized. However, it seems that the fontSiz ...

Are you experiencing issues with the cipher update when using the crypto library?

When using the crypto module for string encryption and the passed string is not 16 bytes, I expected the cipher.update() function to automatically add padding and create a 16-byte string. However, during debugging, cipher.update returned an empty string. I ...

Having trouble with RoR Mongoid Lookup feature?

I have recently started using MongoID ( & mongoDB) and am facing performance issues related to fetching data from a reference collection. class Accounting::Invoice include Mongoid::Document belongs_to :contact, :class_name => 'Contact&apo ...

Revamping HTML Label 'for' with JavaScript: Unveiling Effective Techniques

I'm facing an issue with changing the target of a label that is associated with a checkbox using JavaScript. Here's the code I have: <input type="checkbox" id="greatId" name="greatId"> <label id="checkLabel" for="greatId">Check Box&l ...

Encountered a 404 Error when attempting to store data in mongoDb using node.js and express

Currently, I am facing an issue while trying to save data from Bootstrap input fields into my MongoDB database. Every time I attempt to do so, I encounter the error insertMovie:1 POST http://localhost:3000/insertMovie 404 (Not Found). Despite my efforts to ...

Steps for inserting an image onto a blank page

Struggling with HTML and javascript - need help with displaying an image on a new page: Creating a new page and want to show an image on it: thepage= window.open('', '', 'height=700,width=800,left=100,top=100,resizable=yes,scroll ...

Encountering the error message 'XMLHttpRequest is not defined' while incorporating getServerSideProps() in NextJS

I'm currently exploring NextJS with SSR and encountering an error when trying to fetch data from a Spotify playlist using the spotify-web-api-js library. This issue only occurs when executing on the server side: error - ReferenceError: XMLHttpRequest ...

When trying to validate an HTML form using AJAX, jQuery, and JavaScript, the validation may not

Here is a high-level overview of what happens: The following code functions correctly... <div id='showme'></div> <div id='theform'> <form ...> <input required ... <input required ... <inpu ...

Utilizing regular expressions to search through a .md file in JavaScript/TS and returning null

I am currently using fs in JavaScript to read through a changelog.MD file. Here is the code snippet: const readFile = async (fileName: string) => { return promisify(fs.readFile)(filePath, 'utf8'); } Now I am reading my .md file with this fu ...

A guide on retrieving query string parameters from a URL

Ways to retrieve query string parameters from a URL Example Input - www.digital.com/?element=fire&solution=water Example Output - element = fire solution = water ...