What is the reason this JavaScript code functions properly within a <script> tag but not when placed in a separate .js

After researching various image sliders online, I came across this specific one. It worked perfectly fine when I included the JavaScript directly in a script tag within the HTML file. However, as soon as I tried to link it via a .js file, the slider stopped functioning, and I couldn't determine the root cause of the issue. The console output indicated an error reading "addEventListener" at line 10. Any insights or assistance would be greatly appreciated!

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  overflow: hidden;
}
.
.
.
</footer>
</main>
</body>
</html>

Answer №1

As @evolutionxbox mentioned, it's important to ensure that your JavaScript is included in the right place. If the JS is included in the header or before the elements it references in the HTML, those elements may be null when the script runs.

To avoid this issue, you should make sure your script runs after the document is fully loaded. One way to do this is by wrapping your code in a function and attaching it to the window onload event.

Your script setup could look like this:

function yourScript(){
/* Your script goes here */
}

window.addEventListener("load", yourScript);

Alternatively, you can use:

window.addEventListener("DOMContentLoaded", yourscript);

This will run your script after the DOM has been parsed, but before all external content like images have finished loading. This should work well for most scripts.

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

Each time the Jquery callback function is executed, it will return just once

Whenever a user clicks on the "customize" link, I trigger a function to open a dialog box. This function includes a callback that returns an object when the user clicks "save". The problem is, each time the user clicks "customize", the object gets returned ...

Disable the smooth scroll animation when transitioning between pages using the Link component in NextJS

Not sure if this is a new feature of Next.js, as I didn't encounter this issue in my previous Next.js project. When I reach the bottom of a page and try to navigate to another page, a scroll-to-top animation appears on the destination page. I want to ...

Tips on utilizing browser.getCurrentUrl() within a Protractor examination

I’ve been wrestling with these lines of Protractor code today: element(by.linkText("People")).click(); browser.waitForAngular(); var url = browser.getCurrentUrl(); ... It seems that getCurrentUrl always throws an error when placed after a waitF ...

Is it possible to include a JavaScript script in a Laravel Blade file?

I have an Auth module from nwidart/laravel-Module. I am trying to include a script file in the Modules\Auth\Resources\views\layouts\app.blade.php file, like this: <body> ...... ... <!-- Scripts --> <script s ...

Experiencing Issues with the Email Button Functionality on My Website

I am looking to create an "Email" button that will send the user-entered text to my email address. Here is the code snippet: <form method="post" action="malto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cb ...

Enhance your iPhone web app with high-resolution retina images!

As I develop a mobile web application accessible on any smartphone, I have the index.html file available for review: The app includes 2 jQuery functions. One detects if the user is using an iPhone and displays a bubble with instructions to add it to the h ...

There was an error: "Uncaught TypeError - onPageChange function is not defined for the DataGrid component in Material

I'm struggling to integrate a DataGrid component into my application. While the table renders correctly with the code provided, I encounter an error when clicking on the next page icon - react-dom.development.js:327 Uncaught TypeError: onPageChange is ...

Adjusting the speed of Flexslider with mousewheel control

I am looking to implement flexslider with mousewheel functionality. Here is an example of how I want it to work: $('#slider').flexslider({ animation: "slide", mousewheel: true, direction: "vertical", ...

After loading ajax content onto the page, the scroll bars fail to appear

I am currently constructing a website that loads page content through ajax. Everything seems to be functioning perfectly, except for a peculiar issue I have encountered in Chrome and Safari. Surprisingly, it is working flawlessly in IE! The problem lies i ...

What is the best way to implement a dynamic sidebar component using React and Material UI?

I have been attempting to implement a responsive sidebar using React Material Design, but I am struggling to achieve the desired outcome. The main goal is for the page content to remain responsive when the sidebar is opened, without overlapping on the pag ...

An alternative method for storing data in HTML that is more effective than using hidden fields

I'm trying to figure out if there's a more efficient method for storing data within HTML content. Currently, I have some values stored in my HTML file using hidden fields that are generated by code behind. HTML: <input type="hidden" id="hid1 ...

Basic animation created using Three.js

I'm currently experimenting with a basic color animation in Three.js. Below is the code I am using: const geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); const cube = new THREE.Mesh(geomet ...

Error in Next.js Image Component: Missing SRC

Encountering an error with the next.js image component, specifically related to a missing "src" property. Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {} Th ...

Having numerous bxsliders implemented in a Genesis child theme

I'm currently working on incorporating multiple bxsliders through custom fields in a wp genesis child theme. The initial slider was successfully implemented using the following function within the genesis child theme functions: add_action('genes ...

Alter the color of Material UI Raised Button when it is hovered over

I am trying to change the background color of a raised button on hover in Material UI. I attempted the following, but it did not work. Is there a way to modify the background color in Material UI for a raised button? Example.JS <RaisedButton ...

Guide on displaying JSON data from a server on a webpage using Google Charts in real-time

Although I am not a JavaScript developer or an expert in AJAX, I consider myself a novice desktop developer. I would greatly appreciate it if you could guide me on how to connect an MCU that returns JSON data to a web page using Google gauge, running on th ...

Is it possible to change the transition behavior within a Vue component?

Is there a way to modify or replace transitions within a Vue component? I am currently using Buefy components for my website, but I have encountered an issue with certain components like collapse that have a slot with a fade transition that I do not pref ...

Please select the option to choose all values

Currently, I am working on implementing a select option feature on my webpage. I have integrated PHP into it to ensure that the selected option remains unchanged after submission. My goal is to include a value of "any" so that when the user chooses "ANY," ...

How can one utilize Codemirror code folding while avoiding the use of "[ ]"?

I am looking forward to implementing Codemirror codefolding for folding only braces { and }, as well as comments. However, I am facing an issue where it also folds square brackets [ and ]. Since square brackets are usually part of one-line statements, I do ...

Place the button inside the form following another block element

Here is the HTML code I am working with: <div class="actions"> <input id="submit-car" name="commit" type="submit" value="Добавить объявление"> </div> and here is a fiddle example: http://jsfiddle.net/348U4/ In ...