I am looking to gather user input in JavaScript and then showcase that input on the webpage. What would be the best

I am currently learning Java and I decided to challenge myself by creating a hangman game. The issue I am facing is that when the user inputs a letter, nothing happens - there is no output indicating whether the guess was correct or incorrect. I suspect that I may be mishandling the event in my guessLetter() function. Any guidance on this problem would be greatly appreciated.

window.addEventListener("DOMContentLoaded", function() {
      var word = ['pizza'];

      let randNum = Math.floor(Math.random() * word.length);
      let chosenWord = word[randNum];
      let underScore = [];

      let docUnderScore = document.getElementsByClassName('underScore');
      let docRightGuess = document.getElementsByClassName('rightGuess');
      let docWrongGuess = document.getElementsByClassName('wrongGuess');

      console.log(chosenWord); //for debugging purposes

      let generateUnderscore = () => {
        for (let i = 0; i < chosenWord.length; i++) {
          underScore.push('_');
        }
        return underScore;
      }


      document.onkeyup = function guessLetter(event) {
        let letter = String.fromCharCode(event.keyCode || event.code).toLowerCase();

        if (chosenWord.indexOf(letter) > -1) {
          rightWord.push(letter);
          underScore[chosenWord.indexOf(letter)] = letter;
          docUnderScore[0].innerHTML = underScore.join(' ');
          docRightGuess[0].innerHTML = rightWord;
          if (underScore.join('') === chosenWord) {
            alert('Congratulations! You've won!');
          } else {
            wrongWord.push(letter);
            docWrongGuess[0].innerHTML = wrongWord;
          }
        }
        underScore[0].innerHTML = generateUnderscore().join(' ');

      }
    });
<!DOCTYPE html>
<html>

<head>
  <h1> Hangman Game </h1>
  <div id="guesses">
    <div class="letter" id="letter" </div>
    </div>
</head>

<body>
</body>
<div class="container">
  <div class="underScore">_ _ _ _</div>
  <div class="rightGuess"> correct guesses </div>
  <div class="wrongGuess"> wrong guesses </div>
</div>

</html>

Answer №1

Errors are occurring in the JS console due to the absence of definitions for the rightWord and wrongWord variables.

Answer №2

Have you ever found yourself placing content in the head tag instead of the body tag? It won't appear on your webpage that way. Make sure to always include your HTML tags within the body for proper display.

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

What causes useEffect to trigger twice when an extra condition is included?

Attempting to create a countdown timer, but encountering an interesting issue... This code triggers twice in a row, causing the useEffect function to run twice per second. 'use client' import {useState, useEffect, useRef} from 'react' ...

What are the steps to start using the Intersection Observer API right away?

Utilizing the Intersection Observer API, I can accurately determine whether an element is within the viewport or not. Is there a way to utilize the Intersection Observer API to detect if an element is in the viewport without relying on a callback function ...

A unique column in the Foundry system that utilizes function-backed technology to calculate the monthly usage of engines over a

In my dataset of ‘Engine Hours’, I have the following information: Engine# Date Recorded Hours ABC123 Jan 21, 2024 9,171 ABC123 Dec 13, 2023 9,009 ABC123 Oct 6, 2023 8,936 XYZ456 Jan 8, 2024 5,543 XYZ456 Nov 1, 2023 4,998 XYZ456 Oct 1 ...

Contrast between the act of passing arguments and using apply with arguments

I have an important backbone collection that utilizes a save mixin to perform Bulk save operations (as Backbone does not natively support this feature). // Example usage of Cars collection define([ 'Car', 'BulkSave' ], function(Car ...

The Javascript array does not function like a typical array

I am currently facing a perplexing issue while working with the Twitter API. Below is the script causing the confusion: const Twitter = require('twitter-api-stream') const twitterCredentials = require('./credentials').twitter const t ...

The process of incorporating external JavaScript scripts into VueJS Components

I currently have two external scripts that need to be used for the payment gateways. At the moment, both scripts are placed in the index.html file. However, I prefer not to load these files at the beginning of the process. The payment gateway is only re ...

``The modification of an input value after it has been initially

I find myself in a perplexing situation where I am setting a value to an input element from a route parameter. <input type="search" class="form-control search-control" :value="search"> Below is the search computed function: computed: { search() ...

Methods for passing JavaScript variables to PHP

I have encountered this problem on Stack Overflow before, but I couldn't find a solution that worked for me. I am using Codeigniter and have a form where users can rate a product. What I need to achieve is to insert the user's rating into the dat ...

Steps for installing a package using npm without the need for configuring a package.json file

According to this source, it is feasible to install npm packages before creating the package.json file. After installing nodeJS on my computer, I attempted to run the following command in an empty directory: npm install jQuery This resulted in the follow ...

looping through a linked data object with ng-repeat

I am working with a Node object in my Angular controller. Each Node contains a next property which points to the next item: $scope.Stack = function () { this.top = null; this.rear = null; this.size = 0; this.max_size = 15; ...

Transmit information from a Chrome extension to a Node.js server

Recently, I developed a basic Chrome extension that captures a few clicks on a specific webpage and stores the data in my content_script. Now, I am looking for ways to transmit this data (in JSON format) to my node.js file located at /start. I am seeking ...

Leveraging the Power of CSS in Your Express Applications

Struggling to make my CSS links functional while working on localhost. Currently, when I view Index.html on my server, it displays as plain text without any styling. Even after trying the express middleware, the CSS files are still not being served, result ...

What is the best way to divide my value sets using jQuery?

Within a given string such as 28_34/42/34,23_21/67/12,63_5/6/56, I am seeking to split or eliminate sets based on the ID provided. For example, if the ID is 23, then the set 23_21/67/12 should be removed. To achieve this, I am checking the value after the ...

What are some tactics for avoiding movement in the presence of a border setting?

I created a webpage that has the following structure: .topbar-container { width: 100%; position: fixed; top: 0; background-color: #2d3e50; z-index: 999; display: flex; transition: height 500ms; } @media (min-width: 992px) { .topbar-cont ...

Organizing outcome searches through ajax

I have a result table displayed on the left side https://i.stack.imgur.com/otaV4.png https://i.stack.imgur.com/pp9m0.png My goal is to transform it into the format shown on the right side of the table In a previous inquiry found here, @Clayton provided ...

Serialize a series of select boxes to optimize for AJAX POST requests

To better explain my issue, let's consider a simple example: Imagine I have a form that collects information about a user: <form action="#" method="post" id="myform"> <input type="text" name="fname" /> <input type="text" name= ...

Can a string variable be passed as a file in a command line argument?

Running a command line child process to convert a local file to another format is something I need help with. Here's how it works: >myFileConversion localfile.txt convertedfile.bin This command will convert localfile.txt to the required format an ...

When trying to set the state in the OnMouseOver event, an error is thrown: TypeError - React is

Despite encountering numerous posts discussing this issue, I am struggling to resolve it in my particular scenario. I have a collection of items that I am attempting to apply color changes to (the div's) when they are hovered over. The coloring only ...

Issue: Request from a different origin blocked

I encountered an issue while working on a web project using the PlanGrid API. I am receiving a cross-domain request block error. var apiKey="API KEY"; var password="PASSWORD"; $.ajax({ url: "https://io.plangrid.com/projects", xhrFields: { ...

The AngularJS ng-if directive is failing to function properly, despite the logged boolean accurately reflecting the

I created a custom directive that handles the visibility of text elements on a webpage. While this logic works correctly half of the time, it fails the other half of the time. Here is the code snippet from my directive: newco.directive 'heroHeadline& ...