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

When the button is clicked, a modal will pop up

Looking for help in incorporating JavaScript to create a responsive modal that pops up with lyrics when a button is pressed in a table. Any assistance would be greatly appreciated. Note: Only the code for the table has been provided. Let me know if you&ap ...

Tips for personalizing jQuery formBuilder's typUserAttrsIf you want to

In my Rails app, I've added a new feature that involves using a custom form. After considering various plugins, I decided to go with jQuery formBuilder as my top choice. While I am able to customize the values of each "typeUserAttrs," what I really wa ...

Tips for selecting an <select> option value based on an URL parameter automatically

I have a 2-step form where I am successfully passing the first name in the URL from step 1 to step 2, but I am struggling to do the same for a select field. Here's an example of what I have: In the URL: ?firstname=Bob Form Field: <input type= ...

Concealing Social Security Numbers using AngularJS

I am currently working on masking SSN numbers using AngularJS. Expected Outcome: Before applying mask (onFocus) After applying mask (onBlur) Users are only allowed to enter numbers, and the SSN formatting is handled by filters. Below is a sample of the ...

A simple guide on integrating personalized color palettes into Material-UI Theme

One enhancement I'd like to make in my theme is the inclusion of a custom color called warn import React from 'react' import { MuiThemeProvider } from '@material-ui/core/styles' import createMuiTheme from '@material-ui/core/s ...

What is the best way to transform a standard select input into a React select with multiple options?

Is it possible to transform a regular select dropdown into a multiple select dropdown in React, similar to the one shown in this image? I'm currently using the map method for my select options. https://i.stack.imgur.com/vJbJG.jpg Below is the code s ...

Tips for Identifying Different ID Values of HTML Elements with jQuery

Currently, I have two different divs on my webpage, each containing buttons and hidden fields. When I try to pass the value of the hidden field attached to the button in a jQuery function, I encounter an issue where clicking on the second div results in pa ...

Error: The JSON data contains an unexpected token at the beginning Express

I am currently following a tutorial (here) to establish a connection between Express and React Native. I have a server.js script running which connects to the client (App.tsx) on my IP address using port 3000. The server and app are running simultaneously ...

Conceal flexbox item depending on neighboring element dimensions or content

I've encountered an issue while using a flexbox to display two elements side by side. The left element contains text, while the right one holds a number. When the value in the right element has at least 7 digits ( > 999,999 or < -999,999), I need to ...

retrieving the outcome from a PHP script invoked through Ajax

Having trouble transferring the results of a PHP script to HTML input fields This is my PHP script: $stmt->execute(); if ($stmt->rowCount() > 0){ $row = $stmt->fetch(PDO::FETCH_ASSOC); echo 'Located: ' . $row[&ap ...

When URL string parameters are sent to an MVC controller action, they are received as null values

Are You Using a Controller? public class MyController : Controller { [HttpGet] public ActionResult MyAction(int iMode, string strSearch) { return View(); } } Within my view, I have a specific div with the id of "center" I am runn ...

How can we guide the user to a different page when a particular result is retrieved by AJAX?

Whenever my PHP function makes a database call, I receive multiple results. The ajax then displays these results in a div element. My question is: How can I redirect the user to the next page once I obtain a specific result from the PHP function? Current ...

React MUI: Dynamic and Adaptive sidebar

I'm currently working on integrating React Material UI: Persistent + Responsive drawer to create a responsive layout for mobile devices with a persistent drawer for larger screens. I've come across some code that almost fits my requirements, but ...

How can I retrieve one distinct document for each group based on a shared property value in MongoDB?

I have a database collection set up in MongoDB with a schema like this: var personSchema = new mongoose.Schema({ _id: ObjectId, name: String, // ... alias: String }; (I am using mongoose, but the details are not important). Because I retrieve pe ...

What is the reason behind Angular generating files with 'es5' and 'es2015' extensions instead of 'es6' (or no extension)?

Recently, I installed the Angular CLI (@angular/cli 9.0.1). My goal was to create a new Angular Element, package it, and then integrate it into another application. Following several blog tutorials, I found that they all mentioned the final step of creati ...

Using conditional statements in AngularJS, you can check multiple conditions using the

I am attempting to utilize angular in my slim file, but I'm uncertain how to convert an if else block into angular syntax. Although I am aware that angular does not support ng if else statements, is there a method to modify the code below to work with ...

Ways to customize PreBid.js ad server targeting bidder settings

In an effort to implement a unique bidder setting key name within my prebid solution, I have taken the necessary steps as outlined in the documentation by including all 6 required keys. Is it possible to change the key name 'hb_pb' to 'zm_hb ...

Utilize jQuery to choose a specific tab

I have implemented a jquery tab in my UI. I want to have the second tab selected when the page loads, instead of defaulting to the tab with the "Active" class. Here is my HTML tab code: <div class="typo"> <div class="container-fluid"> ...

Guide on loading xml information from a web browser using JavaScript

I have been working on loading data from the browser using a URL and currently utilizing JavaScript to achieve this. window.onload = function() { // This is the specific URL I am attempting to load data from. // The XML fi ...

Is there a way to seamlessly integrate typeahead.js with jquery.validate?

Currently, I have a website built on ASP.NET MVC 5 which utilizes jQuery validation (specifically 'jquery.validate.js' in the MVC project template). My goal is to implement type-ahead functionality using 'typeahead.js' on an input field ...