Transforming external JavaScript and CSS scripts into HTML code

I am attempting to consolidate an external JS file and CSS file into a single HTML file by incorporating them internally in the HTML. While the CSS is functioning correctly with the style tag, the JS file seems to be causing some issues.

What adjustments should I make in order to properly connect these files?

Below is the external JS file that I obtained online:

    <script>

    function variables(){
        var btn_start = document.getElementById("start");
        var btn_reset = document.getElementById("reset");
        var btn_check = document.getElementById("check");

        var main_div = document.getElementById("main-div");

        var guess_box = document.getElementById("guess-box");
        var all_guesses = document.getElementById("all-guesses");
        var high_or_low = document.getElementById("high-or-low");

        var random_num = Math.floor(Math.random() * 100) + 1;

        var count_guess = 1;
    }
    
    function start() {
        main_div.style.visibility = "visible";
    }

    function checkGuess() {
        var your_guess = Number(guess_box.value);

        if (count_guess <= 10) {
            if (your_guess < random_num) {
                all_guesses.textContent += your_guess + " ";
                high_or_low.textContent = "Your Guess is Low";
                high_or_low.classList.add("wrong");
                count_guess++;
                guess_box.value = '';
            }
            else if (your_guess > random_num) {
                all_guesses.textContent += your_guess + " ";
                high_or_low.textContent = "Your Guess is High";
                high_or_low.classList.add("wrong");
                count_guess++;
                guess_box.value = '';
            }
            else {
                all_guesses.textContent += your_guess + " ";
                high_or_low.textContent = "Congratulations! You Guessed it Right.";
                high_or_low.classList.add("success");
                guess_box.value = '';
                gameOver();
            }
        }
        else {
            all_guesses.textContent += your_guess + " ";
            high_or_low.textContent = "Game Over! Sorry, your chances are over.";
            high_or_low.classList.add("wrong");
            guess_box.value = '';
            gameOver();
        }
    }

    function gameOver() {
        btn_check.disabled = true;
        guess_box.disabled = true;
    }

</script>

Here is where the body is located:

<body>
   <script> 
      // What changes need to be made here?
   </script> 
</body>

Answer №1

To clean up the JavaScript file, eliminate the <script> tag.

Answer №2

It seems like you're looking to embed external JavaScript within your HTML using <script> tags.

To ensure it works correctly, make sure the script is placed after any DOM elements that are being assigned to variables or referenced in the JavaScript code. Otherwise, if the script comes before these elements, it will fail because it will try to access elements that haven't been created yet.

Additionally, ensure that the functions have access to the variables such as guess_box, main_div, etc. If not, the functions won't be able to perform their intended actions.

You can simplify the code by removing the function wrapper from variables() and assigning variables at the top of the script. This way, all functions will have access to these variables within their parent scope. Consider wrapping the code in an IIFE to avoid creating global variables.

<!doctype html>
<html>
<head> 
<!-- head stuff -->
</head>

<body>

<!-- end-user visible DOM elements here before JS -->

<script>
(function (){
  
  var btn_start = document.getElementById("start");
  var btn_reset = document.getElementById("reset");
  var btn_check = document.getElementById("check");

  var main_div = document.getElementById("main-div");

  var guess_box = document.getElementById("guess-box");
  var all_guesses = document.getElementById("all-guesses");
  var high_or_low = document.getElementById("high-or-low");

  var random_num = Math.floor(Math.random() * 100) + 1;

  var count_guess = 1;
    
  function start() {
    main_div.style.visibility = "visible";
  }

  function checkGuess() {
    var your_guess = Number(guess_box.value);

    if (count_guess <= 10) {
      // Game logic
    }
    else {
      // Game over logic
    }
  }

  function gameOver() {
      btn_check.disabled = true;
      guess_box.disabled = true;
  }
})();
</script>
</body>
</html>

Alternatively, you can place the JavaScript code in the head element and use an event listener to execute it once the DOM is fully loaded:

<head>
<script>
document.addEventListener('DOMContentLoaded', init);

function init (){
  // Variable assignments and game logic
  
  /*
    Auto-run start() function here if needed
  */
  start();
    
  function start() {
    // Start function logic
  }

  function checkGuess() {
    // Check guess function logic
  }

  function gameOver() {
      // Game over function logic
  }

}

</script>
</head>
<body>
<!-- body content -->

Using an event listener to run your JavaScript code after the DOM has been parsed by the browser provides another approach to ensuring that the script executes correctly without relying on the order of elements in the HTML file.

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

Attaching an Event Listener to an array

I am struggling with a homework assignment and don't understand why I am receiving an error message saying 'undefined is not an object (evaluating 'buttons[i].style')). Any help would be appreciated. I have been attempting to loop throu ...

Angular 4 - The Promising Outcome: How to Retrieve the Value upon Completion

Is there a way to retrieve a value from a promise and store it in a global variable? I've been attempting to accomplish this, but the global variable remains undefined. import { Injectable } from '@angular/core'; import {ActivatedRouteSnap ...

Is there a way to effortlessly refresh a viewpage with fresh data directly from Firebase?

I am trying to update my HTML page with new data from Firebase in real time without having to refresh the entire page. However, I am facing issues where the view is not updating automatically. How can I achieve this? In my JavaScript file, I query Firebas ...

Display Loading Spinner with Bootstrap on Form Submission

This Django project features a Bootstrap spinner within a button, as seen in the code snippet below: <form method="POST" id="pdfUploadForm" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <b ...

Cannot access jquery within an angular directive

I've been attempting to incorporate jquery-ui's sortable feature on the elements within an ng-repeat loop. The issue I'm facing is that I am unable to actually perform the sortable action on these ng-repeat elements. I have searched for so ...

Prevent span/button clicks by graying them out and disabling the ability to click using HTML and JQuery

I am facing a challenge with my two spans that reveal specific information when clicked. I want to make one span appear as a disabled button (greyed out) when the other span is clicked. I tried using $("#toggle-odd").attr("disabled", tr ...

Tips for sending multiple values in a data object using jQuery AJAX

I am currently working on a form that contains two input fields, with the possibility of more being added later. The first input is a text field and the second is a checkbox. I want to be able to send these inputs using $.ajax. To accomplish this, I have ...

Best Way to Enable Push Notifications on Phonegap for iPhone - Top Suggestion

Looking for advice on the most cost-effective way to add push notifications to an HTML5 Phonegap app. I'm a front-end developer with limited xcode knowledge, so I'm considering using a service like Urban Airship. Any recommendations or tips on im ...

What is the best way to transmit the server response information from a fetch API to the client?

After receiving a response with the expected results from an API call using fetch API and a json object, I am looking for ways to send these results to the client in order to display them on the interface. The server-side operation was conducted through th ...

What is the best way to assign attributes to multiple HTML elements using an array?

Seeking assistance to hide various sections in my HTML file upon button click, with the exception of one specific section. Encountered an error message: Uncaught TypeError: arr[i].setAttribute is not a function Here's a snippet of my code: const hide ...

Uploading Blobs using JavaScript and FormData

Currently, I'm encountering an issue with uploading a blob generated in JavaScript to my server. The main concept involves a user uploading an image, which is then center cropped and downsampled using JavaScript before being transmitted. Although the ...

Adjust the width of the container and rotate the text accordingly

I am looking to display text vertically (like a y-axis chart label) and need the ability to rotate text of varying lengths while keeping it on one line. My attempt to achieve this using CSS3 transforms can be seen in this JSFiddle: .rotate { transform ...

Conceal the rating of WordPress products when they have no ratings

I am looking to remove the star ratings under the title for products with empty reviews. I specifically want to hide the stars without allowing users to leave a new review. I found a similar solution for hiding a different element and attempted to customiz ...

Guide on how to position the icon for the Ant Design datepicker before the input selector rather than after

Looking for a way to set the icon with or without a pseudo element for Ant Design, I've tried a method that isn't working. .ant-picker-input > input::before { content: url('../../public/assets/calendar.svg') !important; margin-r ...

Tips for receiving a reply from S3 getObject in Node.js?

Currently, in my Node.js project, I am working on retrieving data from S3. Successfully using getSignedURL, here is the code snippet: aws.getSignedUrl('getObject', params, function(err, url){ console.log(url); }); The parameters used are: ...

Using PHP Ajax to populate FullCalendar's eventSources

Currently, I am encountering an issue with Fullcalendar V4 related to the eventSources option when using PHP Ajax. My JavaScript code looks like this: var eventSource = "data.php?value1=" + item_id; calendar.addEventSource(eventSource); In my PHP scrip ...

How do I insert a variable into my email content using PHP?

Hey there, I have a form that captures Name, Email, Subject, Telephone Number, Message, and a checkbox. Unfortunately, I'm not very proficient in PHP. I've just started learning the basics and could use some guidance from you :) The Form < ...

Utilizing repl.it for a database in Discord.js

I've created a database script on repl.it and it seems to be functioning properly. However, I keep encountering null values in the users' database. Here's my code snippet: client.on("message", async (message) => { if (messag ...

When attempting to create text with Three.js using the TextBufferGeometry method, an error arises indicating that the property yMax is unreadable due

While trying to add text to a three.js scene, I encountered the error message "Uncaught TypeError: Cannot read property 'yMax' of undefined". let loader = new THREE.FontLoader(); let font = loader.parse( jsonFont ); let geometry = new THRE ...

AngularJS radio buttons can now be selected as multiple options

Currently, I am in the process of learning angular and have implemented a radio button feature in my program. However, I have encountered a perplexing issue that I cannot seem to explain. <!DOCTYPE html> <html> <head> <meta ch ...