Disabling the navbar menu on Ruby on Rails occurs when pages are changed

I am facing an issue concerning the responsive navbar functionality on my website. The problem occurs when the screen width drops below 1024px. Initially, the navbar is designed to switch to a responsive mode upon clicking the burger menu, which is implemented using JavaScript. While this feature works correctly at first, it fails to function properly when navigating between pages (for instance, from the home page to the store page), and I am unable to determine the root cause of this malfunction. Below is the code snippet:

/* Here is the JavaScript implementation */


document.addEventListener('DOMContentLoaded', () => {
  let responsiveMenu = document.querySelector('.responsive-navbar');
  let body = document.querySelector('body');
  let burgerBtn = document.querySelector('.burger-menu');
  let responsiveLinks = document.querySelectorAll('.responsive-menu-links')
  burgerBtn.addEventListener('click', () => {
    burgerBtn.classList.toggle('cross')
    responsiveMenu.classList.toggle('menu-open');
    body.classList.toggle('disable-scroll');
    responsiveLinks.forEach(link => {
      link.classList.toggle('trigger-anim')
    })
  })
})

/* Included partial for _navbar.html.erb file */

<div class="navbar-header">
  <div class="navbar-menu">
    <%=link_to 'Home', root_path%>
    <a href="">About Us</a>
    <a href="">Contact</a>
    <a href="">About Me</a>
    <%=link_to 'Store', store_path%>
  </div>
  <div class="burger-menu">
    <span></span>
    <span></span>
    <span></span>
  </div>
  <div class="responsive-navbar">
  <div class="menu-background"></div>
  <div class="menu-links">
     <%=link_to 'Home', root_path, class: 'responsive-menu-links'%>
      <a href="" class="responsive-menu-links">About Us</a>
      <a href="" class="responsive-menu-links">Contact</a>
      <a href="" class="responsive-menu-links">About Me</a>
      <%=link_to 'Store', store_path, class: 'responsive-menu-links'%>
  </div>
</div>
  <div class="navbar-items">
    <div class="logo">
    </div>
  </div>
</div>

/* Styling rules */

.trigger-anim {
  animation: scaleIn .2s forwards;
}
.menu-open {
  width: 100vw !important;
  a {
    opacity: 1 !important;
  }
}

.disable-scroll {
  overflow: hidden;

  .home-container {
    height: 100vh !important;
    overflow: hidden !important;
  }
}

.cross {
  span {
    &:nth-of-type(1) {
      transform: rotate(40deg) translateY(20px);
    }
    &:nth-of-type(2) {
      transform: translateX(500px);
      opacity: 0;
    }
    &:nth-of-type(3) {
      transform: rotate(-40deg) translateY(-20px);
    }
  }
}

Answer №1

It seems like you are working with Rails and Turbolink, so your event should be set to turbolinks:load instead of DOMContentLoaded. Here's how you can update it:

document.addEventListener("turbolinks:load", function() {
 // Your code here
})

Referencing the Turbolinks documentation:

If you're used to using window.onload, DOMContentLoaded, or jQuery ready events for adding JavaScript behavior, note that Turbolinks will only trigger these events on the initial page load, not on subsequent page changes.

Turbolinks introduces a series of navigation events, with turbolinks:load being the most important one. This event occurs once during the initial page load and then again after every Turbolinks visit.

I hope this clarifies things for you.

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

Optimal method for determining service availability

I am looking for a way to check if my service is currently available. Oddly, I receive success in the ajax() function even when attempting to access certain service methods that are turned off. Instead of receiving expected data, I am greeted with an htm ...

Uncovering the User's Browser Specifically for UC-Mini and Opera-Mini

I'm in need of a script that can identify if the user's browser is uc-mini or opera-mini. These particular browsers do not support the "transition" feature. Therefore, when this specific browser is detected, I would like to deactivate the "trans ...

Load images in advance using this script

Using a script to load images on two websites, the image is placed inside a div with the ID div-to-load-external-image Encountering an issue where PageSpeed Insights advises to preload these images, seeking guidance... Any assistance will be appreciated. ...

Getting an alert message to display using ajax

I have attempted various solutions provided here, but I am unable to display my flash notice on an ajax call. Here is the code snippet from my controller action: def update_email_settings @user = User.find(params[:user_id]) @user.update(user_param ...

After attempting to retrieve local .HTML content with JQuery ajax for the second time, the JavaScript code within index.html appears to be malfunctioning

My apologies for my limited proficiency in English... Currently, I am engaged in phonegap development where I am attempting to utilize JQuery ajax to retrieve local .HTML content and insert this extracted content into the div with the id="next-page" in in ...

Node.js project is set up globally on personal system

Introduction I'm diving into the world of Node.js and eager to learn. NPM has been a game changer for me as I can easily install packages globally and utilize them as standalone applications accessible from anywhere on my system. To my surprise, thi ...

The socket.on() function is not able to receive any data

I am encountering an issue with implementing socket.on functionality $('#showmsg').click(function() { var socket = io.connect('http://localhost:3000'); var msgText = $('#msgtext'); socket.emit('show msg', msgText.va ...

Internet Explorer (on mobile devices) does not display submenus when touched

Hello, I have a query about displaying a sublist on touch. I have created a sublist that is supposed to show up when you hover over it. You can view the demo here: @import url(//fonts.googleapis.com/css?family=Titillium+Web:400,200,300,600,700); body { ...

Finding Corresponding Values in an Array with JavaScript

I am working with an array of objects that have a specific format: [ { "card_details": { "cardType": "gift" }, "merchant_details": { "merchantName": "Walter Heisenberg1", "timeZone": "+05:30", } }, { "card_detai ...

Footer refuses to stay anchored at the bottom of the page

I'm struggling to keep my footer at the bottom of all pages on my blog. I am facing two main issues. If I use position:absolute, the footer ends up in the middle of the main blog page. Alternatively, when I don't use it, the footer sticks to the ...

Issue with jqPlot angle setting

I'm having trouble displaying my labels at an angle. Even after attempting to use jqplot.canvasAxisTickRenderer.js as suggested by someone, I keep encountering the following error when I add a reference to it: Uncaught TypeError: Cannot read property ...

Currently, I am developing a customized stylesheet specifically designed for Internet Explorer versions 10 and 11

Is it possible to utilize this straightforward script for identifying IE versions 10 and 11? if($.browser.version == 11.0 || $.browser.version == 10.0) { $("body").addClass("ie"); } ...

Rows that intersect - Challenging to articulate - Bootstrap 3

I'm at a loss for words when trying to describe what I'm attempting without simply showing you a picture: The issue I'm encountering is that the search box's height isn't fixed, and I might want to include other elements on the le ...

What is the proper way to refer to an array or object within a function in JavaScript

Greetings! I am facing an issue with a JavaScript array declared outside of a function as shown below: var daily = []; daily["data"]=[]; daily["data"].push('hello'); function demo() { console.log(daily); // not working here } Can anyone advise ...

How to eliminate ampersands from a string using jQuery or JavaScript

I'm having trouble with a seemingly simple task that I can't seem to find any help for online. My CSS class names include ampersands in them (due to the system I'm using), and I need to remove these using jQuery. For example, I want to chan ...

What steps can be taken to restore the original order of the list if the AJAX request fails?

I'm currently working with the Sortable JS library in combination with jQuery to trigger an AJAX request whenever the list order is modified. Here's how I've implemented it: <ul id="items"> <li>item 1</li> <li>it ...

Unable to make a POST request using axios

I'm having trouble populating a table using vue.js and axios in my visual studio project. Every time I run the solution, I see an empty table with just the heading Title. I experimented with another POST request method but unfortunately, it didn&apos ...

Retrieve the JSON object's name and loop through its child objects

Just diving into JavaScript and web development, seeking some guidance. I'm currently working on gathering information to format and trigger another request. Here's what I have so far: JavaScript $( document ).ready(function(sb_shows) { $. ...

When I include a scrollbar in the popover window, the bootstrap popover arrow disappears

I'm experiencing an issue where the arrow appears when there is no scrollbar, but disappears once I add a scrollbar to the popover content. I haven't been able to replicate this on jsfiddle, so I'm sharing the code here. CSS .pop-div .popo ...

Determine the vertical scrolling and the width of the window in a specific function

I need assistance with displaying a div based on the window width. The requirement is for the div to show when the window width is 1350px or wider. However, if the window is narrower than 1350px, the following rules apply: 1) The div should be hidden if t ...