What are the differences between incorporating JavaScript directly into HTML and writing it in a separate file?

I need help converting this JavaScript embedded in HTML code into a standalone JavaScript file. I am creating a toggle switch that, when clicked, should go to a new page after the transformation. I am looking for the non-embedded version of the function. Here is the code snippet:

<div class="statement">Slide to Play!</div>
<div class="container">
<div class="play" onclick= "this.classId.toggle('active')"> 
<div class="inner-square"></div>
</div></div>

This is the JavaScript code that I have tried but it's not working:

const transition = document.querySelector('play');
Promise.all(
    document.getElementById("play").onclick = function() {
        transition.addEventListener('transitionend', () => {
            console.log('Transition ended');
            location.assign("gamepage.html")
    }
);

Promise.all(
    
    })
).then(transition.addEventListener('transitionend', () => {
    console.log('Transition ended');location.assign("gamepage.html")});

Answer №1

Could it be a scenario where the javascript is running prior to the complete loading of the DOM? Referencing the recommendations outlined in this post $(document).ready equivalent without jQuery

To resolve, encapsulate your javascript within the following:

document.addEventListener("DOMContentLoaded", function(event) { 
  //perform tasks
});

This adjustment should guarantee that the entire HTML content of the page is fully loaded before your javascript code is executed. In case it was functioning when directly inserted into the page, it might have been due to having placed the script before the closing tag, ensuring the complete loading of the page by that point.

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

Output of ngResource compilation

Is there a way to retrieve a single result from my array $scope.trailers? I am encountering an issue where accessing the first index using $scope.trailers[0] returns undefined. The API call is made using ngResource. function getTrailers(pageNo){ ...

Conceal Bootstrap 3 tooltip

There's a tooltip attached to a button within a bootstrap dropdown. Whenever I click that button, the original button is hidden and another button is displayed. However, the tooltip from the previous button remains visible until I scroll vertically or ...

Storing duplicate code in multiple cache files using ReactJS ServiceWorker

I am currently working on integrating a serviceworker into an existing React application that has the following filesystem layout: Filesystem The initialization code is stored in the public folder, while the main code resides in the src folder. In my serv ...

issue concerning slide functionality and ajax integration

I'm facing an issue with the structure of my HTML. Here is the setup I have: <div id ="slide1"> <form method="post" id="customForm" action=""> //my content - name, email, mypassword, pass2 </for ...

My intention is to personalize the react-select component to suit my needs

My task involves changing the size of the arrow to be smaller and positioning it under the circle. Despite setting the width and height in the CSS, the desired effect is not achieved. To align with the UI requirements, I need to adjust the swiper-button- ...

Handling concurrent requests in DjangoDiscover how Django manages multiple simultaneous requests

Handling multiple requests in a web application can be a challenging task, especially when the server needs to perform complex operations like making API requests and executing database queries. In this post, we will explore how Django can effectively mana ...

Show information from the console logger

I'm currently working on displaying data from a database in an HTML page. While the data is showing up in my console, I'm struggling to figure out how to present it in an HTML table format. I'm unsure about the specific function that needs t ...

Use the `fetch` method in JavaScript/TypeScript to make an API call to an IPFS URI but be prepared for potential issues like CORS restrictions, network errors, or

I am currently working on a Next.js project with TypeScript in the browser, and I need to execute the following fetch request: const tokenURIResponse = await fetch( "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg ...

What can be done to avoid a form being reset when it returns no results?

I've recently created a mysql and php search page, which is working well. However, I noticed that when the form is submitted and there are no results returned, the <option> tags get reset. Is there a way to prevent this from happening? META: I ...

Sharing JSON data between PHP and JavaScript/AJAX

In order to validate strings on my website, I am developing a validation mechanism using both Javascript and ajax for client-side validation and PHP for server-side validation. It is essential for both PHP and Javascript to utilize the same variables, suc ...

Troubleshooting React on an Apache Server: A Comprehensive Guide

An interactive React application utilizing React Router has been successfully deployed on an Apache server. After making modifications to the .htaccess file, most of the routes function correctly as intended. Some specific routes within the app rely on us ...

Monitoring of access controls on Safari during uploads to S3

Safari 10.1.2 Encountering an issue intermittently while attempting to upload PDF files to S3 using a signed request with the Node aws-sdk. Despite working smoothly 90% of the time, have been pulling my hair out trying to resolve this problem. Could it be ...

A single pledge fulfilled in two distinct ways

My code ended up with a promise that raised some questions. Is it acceptable to resolve one condition with the token string value (resolve(token)), while resolving another condition with a promise of type Promise<string>: resolve(resultPromise); con ...

Customizing the tab content background color in MaterializeCSS

I've been struggling to customize the background color of my MaterializeCSS tabs content by referring to their official documentation: If you visit the website, you'll notice that the default tabs have a white background, while the 'Test 1& ...

Connecting JSON objects based on unique GUID values generated

I am in search of a method to automate the laborious task of linking multiple JSON objects with random GUIDs. The JSON files are all interconnected: { "name": "some.interesting.name", "description": "helpful desc ...

How to send URL parameters to a different page with the help of express and Node.js

Hey there, I'm currently working on a chat app which you can check out here. I'm in the process of enabling users to join specific rooms by typing in a URL like , assuming they are logged in. I manage user login and signup with passwords. Here&ap ...

Steps for updating a JSON entry in a Node.js environment

What is the best way to update a JSON value using node.js? I have come across a few examples online, but my situation is a bit more complex. I am able to access the value that needs to be modified var contents = fs.readFileSync("./../../skill.json"); var ...

Transitioning from the login screen to the main page in Ionic with the help of Angular

My code is running smoothly, but I encountered an issue when clicking the login button. It changes the state as depicted in the image, altering the URL but failing to open the subsequent page. Can anyone provide guidance on how to redirect to the next page ...

Enable or disable options with the user's permission

Currently, I am developing a WordPress plugin that will display a simple div on all pages. The code is set up to create the div, turn it into a shortcode, and then show it on each page. I want to include a checkbox in the admin settings so that users can ...

Error: When executing the npm run build command, I encountered a TypeError stating that Ajv is not a

I keep encountering an issue whenever I try to execute npm run build error: /node_modules/mini-css-extract-plugin/node_modules/schema-utils/dist/validate.js:66 const ajv = new Ajv({ ^ TypeError: Ajv is not a constructor at Object.<anon ...