Why won't Vanilla JavaScript work with my Rails application?

Having trouble implementing a full screen menu, no Rails errors but not working when project is run. Error received:

Cannot read property 'addEventListener' of null

JS code snippet:

(function() {

  var Menu = (function() {
    var burger = document.querySelector('.burger');
    var menu = document.querySelector('.menu');
    var menuList = document.querySelector('.menu__list');
    var brand = document.querySelector('.menu__brand');
    var menuItems = document.querySelectorAll('.menu__item');

    var active = false;

    var toggleMenu = function() {
      if (!active) {
        menu.classList.add('menu--active');
        menuList.classList.add('menu__list--active');
        brand.classList.add('menu__brand--active');
        burger.classList.add('burger--close');
        for (var i = 0, ii = menuItems.length; i < ii; i++) {
          menuItems[i].classList.add('menu__item--active');
        }

        active = true;
      } else {
        menu.classList.remove('menu--active');
        menuList.classList.remove('menu__list--active');
        brand.classList.remove('menu__brand--active');
        burger.classList.remove('burger--close');
        for (var i = 0, ii = menuItems.length; i < ii; i++) {
          menuItems[i].classList.remove('menu__item--active');
        }

        active = false;
      }
    };

    var bindActions = function() {
      **burger.addEventListener('click', toggleMenu, false);**
    };

    var init = function() {
      bindActions();
    };

    return {
      init: init
    };

  }());

  Menu.init();

}());

New to using vanilla - any extra steps needed to use it in Rails? (via 'require' or something? built-in? Thanks!

HTML code snippet:

<!DOCTYPE html>

<head>

<title>AaP</title>
<%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>

<%= csrf_meta_tags %>

</head>

<body>

<div class="header">
<h1>ASHLEIGH</font> <font color=#f6f6f6>/</font> <font color=#fbe2d4>ALMEIDA</font></h1>
  <div class="burger">
    <div class="burger__patty"></div>
    <div class="burger__patty"></div>
    <div class="burger__patty"></div>
  </div>
<nav class="menu">
    <div class="menu__brand">x
      <a href=""><div class="logo"></div></a>
    </div>
    <ul class="menu__list">
      <li class="menu__item"><a href="" class="menu__link">About</a></li>
      <li class="menu__item"><a href="" class="menu__link">Work</a></li>
       <li class="menu__item"><a href="" class="menu__link">Contact</a></li>
      <li class="menu__item">
        x</i></a>
      </li>
      <li class="menu__item">
        x
          <i class="fa fa-dribbble"></i></a>
      </li>
    </ul>
  </nav>

</div>

Answer №1

If you're encountering this error, it's likely because the script is being executed before the DOM has finished loading and parsing. This means that the specific "burger" div does not yet exist at that point in time.

To resolve this issue, make sure to wrap your code within the DOMContentLoaded handler. You can learn more about this method here: https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

Answer №2

It appears that the issue is with the burger being null in the code. This suggests that your JavaScript may be running before the DOM has fully loaded.

To address this, you will need to assess the sequence of loading elements. Currently, the JavaScript is set to load by default at

<%= javascript_include_tag "application" %>
.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title><%= content_for?(:title) ? yield(:title) : "Example" %></title>
    <%= stylesheet_link_tag    "application" %>
    <%= javascript_include_tag "vendor/modernizr" %>
    <%= csrf_meta_tags %>
  </head>

  <body>
    <%= render "static_pages/header" %>
    <%= yield %>
    <%= javascript_include_tag "application" %>
  </body>
</html>

Therefore, consider moving the

<%= javascript_include_tag "application" %>
below <%= yield %>

and see if that resolves the issue.

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 event fails to propagate up to the parent component

I have a project structure set up as follows: https://i.stack.imgur.com/bvmK5.jpg The todo-form component triggers the created event and I am looking to handle this event in the todos component. todo-form.component.html: <form class="todo-form" ( ...

Can the image be adjusted based on different time zones around the world?

How can I create an HTML banner that changes images based on the time of day? I want one image to display between 7pm and 6am, and another image during the rest of the day. I came across a helpful website that achieves this by changing the image according ...

Pausing and then resuming an interval function within the same function

I'm struggling with an $interval function that runs every second. The function retrieves user credentials from local storage and checks if they have expired. If they have, it refreshes them with new ones. Otherwise, it does nothing. This is what my ...

Following the submission of a POST request, an error occurred stating: "Unable to assign headers once they have been sent to

I'm having trouble figuring out what's wrong with my code. Whenever I send a post request, I get an error message saying "Cannot set headers after they are sent to the client". My model includes a comment schema with fields for user, content, and ...

Creating a visually stunning image grid akin to the meticulously designed layouts found

Forgive my lack of knowledge, but I'm curious about how to create an image or text grid similar to Tumblr using HTML and CSS. I'm looking to achieve a layout like this: ...

What is the method for selecting the desired month on a primeng calendar with multiple selection enabled?

I am looking for a solution to make my inline primeNg Calendar display the month of a specific date in the model, and when I remove dates from the model, I want it to show the current month. I have tried using defaultDate={{value}} and minDate={{value}}, a ...

Can WebSocket messages be encoded?

Is there a way to encrypt or obscure the data I transmit via websockets? For example, the message looks like this: var encryptedMsg = { type: "message", data: { message: "Hello world!" } } I require the ability to send this message in ...

Eliminating Non-Breaking Spaces with the Click of a Button

Having some difficulty with the following Javascript code. I'm not very skilled in writing Javascript, so any assistance on adjusting it to replace any &nbsp; with a regular space would be greatly appreciated. Thank you function copyToClipboard( ...

Can Javascript (PWA) be used to detect fake GPS or mock GPS in applications?

Looking for a solution to prevent users from using Fake Location tools in my PWA application that gathers absence location data. Is there a method or package in JavaScript to detect the presence of Fake GPS installed on the device? ...

Trouble getting proper alignment displayed with JavaScript and CSS

If anyone has a solution for printing content in a div using JavaScript and CSS, please help. The main div with the id 'preview' contains content taken from a database using PHP and MySQL. However, the data on the print page appears vertically an ...

Div scrolling allows for parallel viewing of PDFs in a side by side arrangement

I have two scrollable elements on my webpage: one positioned on the left side and the other on the right side. The left element is a regular div, while the right element is an object containing an embedded PDF. <object width="100%" height=&quo ...

Creating a Rails partial from JSON data with a custom rake task

Currently, I am utilizing a helper function: def fetch_static_blog_posts Rails.cache.fetch("blog_posts", :expires_in => 30.minutes) do url = URI('http://www.xxxxxxxx.com/blog/?json=get_recent_posts') request = Net::HTTP.get(url) ...

Error 404: Page not found. Sorry, we couldn't locate the Node JS and Express resource

I have been trying to access the routes /api and /api/superheroes, but I keep encountering an error message whenever I try. Not Found 404 NotFoundError: Not Found at C:\Users\mikae\Desktop\Project\node-express-swig-mongo\a ...

Adapting JavaScript functions from IE to work on Firefox and Chrome: A comprehensive guide

I have encountered an issue with a function that retrieves the selected text range within a contenteditable div. While it works perfectly fine in Internet Explorer, it doesn't seem to work in Firefox and Chrome. Could someone kindly provide guidance ...

How can text be concealed within an input field?

My degrees converter code is functioning well, but I have an issue. When I input a number for one temperature type, the conversion for the other two types is displayed correctly. However, if I then enter a number for another temperature type, the previous ...

Node Signature Generation for Gigya Comment Notifications

I am currently using the Gigya Comment Notification service within my node application and attempting to generate a valid signature. Despite following the documentation, my code is producing an incorrect hash. Below is the code I am using: var crypto = r ...

Using local storage with github sites can lead to some unexpected and peculiar behavior

Currently, I am working on a simple clicker game using HTML and JavaScript. To store the variables money and taxCollecters, I have implemented local storage. However, I am encountering strange issues when trying to use the save and load buttons on the Gi ...

Rest assured, with Ajax Security, your protection is in good

I am currently developing a browser game that heavily utilizes AJAX instead of page refreshes. The combination of PHP and JavaScript is being employed for this project. However, during the course of my work, I became aware of the potential security vulnera ...

Creating a list repeater using v-for in Vue.js 2 with computed property

Seeking assistance with adding computed columns to a table (last three columns). Suspecting the issue lies in the computed property not correctly referencing the record. Any simple solutions that I might be overlooking? Appreciate any thoughts or insights! ...

Using jQuery to follow a div while scrolling that halts at a designated top or bottom boundary

I've been working on this jsfiddle: https://jsfiddle.net/3ncyxnzt/ Currently, the red box stops at a specified margin from the top of the page but I want it to also stop before reaching the bottom, so that it doesn't go under or over the footer. ...