JS ReferenceNotFoundError

There is an issue with some JavaScript code that functions correctly on one website but not on another, even though the code is identical.

The goal of this script is to switch the top navigation to a fa fa-bars Menu when viewed on a mobile device or when the browser window size is reduced.

It successfully works on www.motorsport-tech.com. However, it results in an "Uncaught ReferenceError: myFunction is not defined" error on www.skyforestinn.com.

I have placed this script right before the closing body tag:

<script>
    function myFunction() {
        var x = document.getElementById("navDemo");
        if (x.className.indexOf("w3-show") == -1) {
            x.className += " w3-show";
        } else {
            x.className = x.className.replace(" w3-show", "");
        }
    }

    // Close the modal when user clicks outside of it
    var modal = document.getElementById('ticketModal');
    window.onclick = function(event) {
      if (event.target == modal) {
        modal.style.display = "none";
      }
    }
</script>

To invoke the script in the HTML, I use:

onclick="myFunction()"

Being relatively new to JavaScript, I've looked at multiple solutions for this same issue without success. It's puzzling that the code behaves differently on different websites. Can anyone please assist me in identifying what's incorrect here (besides my lack of expertise) or point me towards the right solution?

Answer №1

This is the script extracted directly from the website:

// Function to toggle the menu on small screens by clicking on the menu button
function myFunction() {
  var x = document.getElementById("navDemo");
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else {
    x.className = x.className.replace(" w3-show", "");
  }
}
// Closing the modal when user clicks outside of it 
var modal = document.getElementById('ticketModal');
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

Initially, this script seems to be ineffective as it exists in one line within a comment block.

To ensure proper functionality, format the script correctly like so:

<script>
// Function to toggle the menu on small screens by clicking on the menu button
function myFunction() {
  var x = document.getElementById("navDemo");
  if (x.className.indexOf("w3-show") == -1) {
    x.className += " w3-show";
  } else {
    x.className = x.className.replace(" w3-show", "");
  }
}
// Closing the modal when user clicks outside of it 
var modal = document.getElementById('ticketModal');
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}
</script>

Additionally, consider moving the script into a separate file for better organization and easier editing, as shown below:

<script src="myscript.js" defer></script>

By putting the script in a separate file like myscript.js, managing and identifying issues will become more streamlined.

Answer №2

There is a certain website that has been optimized to eliminate all line breaks, meaning that a single-line comment will render the following code unreadable.

If you encounter this issue and don't want to go through the lengthy process of finding the setting responsible for removing line breaks, consider using a multi-line comment /* */ instead.

<script>
    function toggleNav() {
        var menu = document.getElementById("navMenu");
        if (menu.className.indexOf("show") == -1) {
            menu.className += " show";
        } else {
            menu.className = menu.className.replace(" show", "");
        }
    }

    /* Close modal when user clicks outside of it */
    var modal = document.getElementById('myModal');
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
</script>

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

Exploring nested checkboxes in ReactJS using mapping techniques

I have a function that triggers child checkboxes once the main checkbox is checked, and all these checkboxes are mapped from JSON data. The main checkboxes (highest level) and all of their children checkboxes (2nd level) underneath them are shown on click ...

Develop a payment confirmation session using Stripe and Node.js

I have set up a POST request using Stripe to handle customer payments let paymentData = { errorMsg:'', key: process.env.STRIPE_PUBLIC_KEY } const session = await stripe.checkout.sessions.create({ payment_method_types: ...

Tips for creating a stylish ReactJs Header component that stays fixed at the top of the page

Having an issue with my Header component - I want it to remain fixed at the top while scrolling down. Here's the current code: I've attempted using "position = fixed", but it caused my header to resize. Then, I tried setting its width to "width ...

When I decide to incorporate both BootstrapVue and Vuetify CSS frameworks into a single project

Can I incorporate two CSS frameworks into my current Nuxt.js project? Does anyone have any insight on why it might be beneficial to use two different CSS frameworks in a Vue.js project? Please provide some guidance on this matter. I am looking to optimize ...

Utilizing unique background images tailored to different screen resolutions

In order to enhance the user experience on my website, I am looking to implement a feature that dynamically changes the background images based on the user's screen resolution. My plan is to use a small snippet of JavaScript within the <head> s ...

Angular UI Bootstrap collapse directive fails to trigger expandDone() function

I am currently utilizing UI Bootstrap for Angular in one of my projects, and I have developed a directive that encapsulates the collapse functionality from UI Bootstrap. Here is how it looks: app.directive( 'arSection', ['$timeout', fu ...

angular-chart custom tooltip positioning issue

Hello everyone! I'm having trouble fixing the tooltip position when hovering over a point. I've searched through various posts on StackOverflow and have tried all the examples provided in my implementation: https://github.com/chartjs/Chart.js/tr ...

The <br/> tag is not functioning properly when retrieving text from a MySQL query

Currently, I am involved in a project that involves an A.I pushing text onto a MySQL database. Our goal is to display the ongoing writing process on a webpage. We are still actively working on this. We are retrieving the data and regularly checking the da ...

steps to extract routing into its own component

Is it possible to extract this routing logic into a separate component? I attempted to use map but it didn't work I want to have only a single route, and change the 'path' when a specific link is clicked const Home = ({ code }) => { re ...

Bootstrap Toggle Button with Dropdown Menu

I have a button-group with font awesome icons and a dropdown on one of them, as illustrated in the example below. I am trying to toggle the button status, but for some reason, the 'active' class is automatically removed on mouseout. It seems to ...

How can I use variables to show the second dropdown list only when a value has been selected in the first dropdown?

Is there any way I can choose a specific value from a dropdown list and based on that selection, show another dropdown list? I understand how to do it with regular words, but what if I use variable names? University Name: <select name="university" id=" ...

Tips on creating vertical stacked content utilizing CSS

Has anyone come across this game before? https://i.sstatic.net/hFX9o.png I am trying to stack each card in a column, here is my fiddle jsfiddle. In my scenario, I have cards wrapped in div elements with a maximum height. If a card exceeds this height, i ...

What sets BoxBufferGeometry apart from BoxGeometry in Three.js?

I'm currently diving into the world of Three.js and I've hit a roadblock trying to distinguish between BoxBufferGeometry and BoxGeometry. Can anyone shed some light on this for me? ...

A-Frame VR: Image missing from display on Chrome browser

UPDATE: I discovered that the issue was caused by running the HTML file from my local hard drive instead of a web server. Once I uploaded it to my web server and ran it from there, everything worked perfectly. A-Frame Version: 0.4.0, Chrome: 55.0.2883.87, ...

Discovering the content within table cells by utilizing JavaScript functions linked to specific IDs

I am currently working on a project that involves a dropdown list: <select id="itemsList" onchange="gettingList()"> <option>Please choose an option</option> <option value="50">Shampoo</option ...

What is the downside of exporting all components into one index.js file?

My approach involves exporting all components to an index.js file, allowing me to easily import them into any other file with the code snippet below. This method is not only straightforward but also keeps my code cleaner. import { RocketCard, Container, Na ...

Is it possible to trigger an event for only one connected client instead of broadcasting it to all clients using socket.io?

I am seeking a way to send an event to just one connected client, rather than broadcasting it to all clients using io.emit(). ...

Strange occurrences observed on array mapping post-state alteration

Greetings to all during these challenging times! Currently, I am delving into Firebase and ReactJS and have encountered a peculiar issue involving state updates in React and the array map functionality in JavaScript. Below is the code snippet showcasing my ...

Issues with Jquery Autocomplete feature when using an Input Box fetched through Ajax requests

When a user selects an option from the drop-down list, an input box is dynamically added to the page using AJAX. document.getElementById("input_box").innerHTML ="<input id='ProjectName'/>"; However, there seems to be an issue with jQuery ...

The div is obscured by the background image

Could someone please assist me in preventing the .background image from overlapping with the skills div when the viewport expands either vertically or horizontally? I've tried several approaches without success. Any help would be greatly appreciated! ...