JavaScript code does not appear to be functioning within my HTML document

As I delve into learning HTML/CSS/JavaScript, I encountered a problem while attempting to create a basic rock-paper-scissors game. Despite believing that my code is correct, it simply won't run. Searching the internet for solutions has yielded no results. With limited JavaScript experience, I'm currently honing my skills through Codecademy. However, it seems that different websites offer conflicting syntactical advice. At this point, I'm unsure of what went wrong and which source is accurate.

<html>
<head>
    <title>R,P,S!</title>
    <script type="text/javascript">
        function whole(){
            function game(play){
                if (play="yes"){
                    var userChoice = prompt("Do you choose rock, paper or scissors?");
                    var computerChoice = Math.random();
                    if (computerChoice < 0.34) {
                        computerChoice = "rock";}
                    else if(computerChoice <= 0.67) {
                        computerChoice = "paper";}
                    else {
                        computerChoice = "scissors";
                    }
                    function compare(choice1,choice2){
                        if (choice1==choice2){
                            compare(userChoice,computerChoice);
                        }
                        if (choice1=="rock"){
                            if (choice2=="scissors"){
                                document.getElementById("result").innerHTML="Rock wins";
                            }
                            else{
                                document.getElementById("result").innerHTML="Paper wins";
                            }
                        }
                        if (choice1=="paper"){
                            if (choice2=="rock"){
                                document.getElementById("result").innerHTML="Paper wins";
                            }
                            else{
                                document.getElementById("result").innerHTML="Scissors win";
                            }
                        }
                        if (choice1=="scissors"){
                            if (choice2=="paper"){
                                document.getElementById("result").innerHTML="Scissors win";
                            }
                            else{
                                document.getElementById("result").innerHTML="Rock wins";
                            }
                        }
                    };
                    compare(userChoice,computerChoice);
                }
                else{
                    document.writeln("<p>Thanks for playing! This was made by Alex</p>";)
                }
            }
            var start = prompt ("Do you want to play?","Yes");}
    </script>
</head>
<body style="text-align:center">
    <h1>JavaScript on a webpage? This is madness!</h1>
    <h2>Madness? THIS... IS... HTML!!!!</h2>
    <button onclick="whole()">Try it out!</button>
    <p id="result">Who won?</p>

</body>
</html>

**Edit: It appears that Codecademy's glossary agrees with other websites, they just haven't gotten around to editing their lessons yet.*

**Edit: Here's my final little code for it. Enjoy its simplicity!*

<html>
<head>
    <title>R,P,S!</title>
    <script type="text/javascript">
        function whole(){
            function game(play){
                if (play=="Yes"||play=="yes"){
                    var userChoice = prompt("Do you choose rock, paper or scissors?");
                    var computerChoice = Math.random();
                    if (computerChoice < 0.34) {
                        computerChoice = "rock";}
                    else if(computerChoice <= 0.67) {
                        computerChoice = "paper";}
                    else {
                        computerChoice = "scissors";
                    }
                    function compare(choice1,choice2){
                        if (choice1==choice2){
                            alert("It was a tie!");
                            game("yes");
                        }
                        if (choice1=="rock"){
                            if (choice2=="scissors"){
                                document.getElementById("messages").innerHTML="";
                                document.getElementById("win").innerHTML="You win. Rock crushes scissors.";
                                document.getElementById("loss").innerHTML="";
                            }
                            else{
                                document.getElementById("messages").innerHTML="";
                                document.getElementById("loss").innerHTML="You lose. Paper smothers rock.";
                                document.getElementById("win").innerHTML="";
                            }
                        }
                        else if (choice1=="paper"){
                            if (choice2=="rock"){
                                document.getElementById("messages").innerHTML="";
                                document.getElementById("win").innerHTML="You win. Paper smothers rock.";
                                document.getElementById("loss").innerHTML="";
                            }
                            else{
                                document.getElementById("messages").innerHTML="";
                                document.getElementById("loss").innerHTML="You lose. Scissors cut paper.";
                                document.getElementById("win").innerHTML="";
                            }
                        }
                        else if (choice1=="scissors"){
                            if (choice2=="paper"){
                                document.getElementById("messages").innerHTML="";
                                document.getElementById("win").innerHTML="You win. Scissors cut paper.";
                                document.getElementById("loss").innerHTML="";
                            }
                            else{
                                document.getElementById("messages").innerHTML="";
                                document.getElementById("loss").innerHTML="You lose. Rock crushes scissors.";
                                document.getElementById("win").innerHTML="";
                            }
                        }
                        else{
                            alert("Very funny. Now do it right.");
                            game("yes");
                        }
                    };
                    compare(userChoice,computerChoice);
                }
                else{
                    document.getElementById("messages").innerHTML="Well alrighty then.";
                    document.getElementById("loss").innerHTML="";
                    document.getElementById("win").innerHTML="";
                }
            }
            var start = prompt ("Do you want to play?","Yes");
            game(start);}
    </script>
    <style>
        body{
            text-align:center;
        }
        #messages{
            font-size:20px;
            color: #00246B;
        }
        #win{
            color: #29A329;
            font-size:18px;
        }
        #loss{
            color:#CC0000;
            font-size:18px;
        }
        a{
            text-decoration:none;
            color:black;
        }
        a:hover{
            font-size:125%;
            color:#B20000;
        }
        button{
            font-size:21px;
        }
    </style>
</head>
<body>
    <a href="http://youtu.be/T8r3cWM4JII">
    <h1>JavaScript on a webpage? This is madness!</h1>
    <h2>Madness? THIS... IS... HTML!!!!</h2>
    </a>
    <button onclick="whole()">Try it out!</button>
    <p id="messages">Who won?</p>
    <p class="result"><span id="loss"></span><span id="win"></span></p>
</body>
</html>

Answer №1

Your code contains a syntax error. Don't forget to put a semicolon after the parenthesis.

else {
    document.writeln("<p>Thanks for playing! This was made by Alex</p>");
}

Remember to call the function game inside the closure at the end of the function whole.

For example:

function() whole(){ 
   function game(play) {
      // your logic
   }

   var start = prompt("Do you want to play?", "Yes");

   game(start);
}

Your game logic has some errors. Make sure to double-check your logic.

You are creating infinite recursive calls when choice1 == choice2.

You can fix this issue by commenting out the following line:

if(choice1 == choice2) {
    // compare(userChoice, computerChoice);
}

This modification should resolve the problem.

Answer №2

Your code has a couple of errors that need to be addressed:

In the if statement, you have used the assignment operator instead of the comparison operator:

if (choice = "correct")

This will just assign the string "correct" to the variable choice. You should use a comparison operator like this:

if (choice === "correct")

You also have a misplaced semi-colon in the following line of code:

alert("Congratulations! You got it right!");)

The correct version should look like this:

alert("Congratulations! You got it right!");

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

Using Vue.js along with vuex and axios allows for data retrieval only upon the second load

After creating a Vue.js app with vuex as a central store and using axios for basic API calls, I implemented the following store action: loadConstituencyByAreaCodeAndParliament({commit}, {parliament_id, area_code}) { axios.get('/cc-api/area-code/ ...

Bootstrap Datepicker, ensuring error-free date selections for check-in and check-out dates

I have encountered some issues while using the bootstrap date picker. If you visit this website, you will find an example of a check-in and check-out selector. When I choose Feb 8th as my arrival date and Feb 9th as my departure date, and then go back to ...

Tips on incorporating a URL from a text file into a string

Could anyone assist me in adding a URL text file containing just one sentence and saving it as a string? Your help would be greatly appreciated. Thank you. ...

Unexpected Behavior: Performance API Issue in Vue.js with Javascript Integration

Currently, I am working on a small project which requires me to calculate the time taken for each page to load. To achieve this, I am utilizing the Performance API. Specifically, I am using the getEntriesByName() method within the Performance API as demons ...

Support for SBE protocol within the grpc/javascript framework

Our plan is to utilize grpc for communication between web UI and server, as well as implement SBE as our communication protocol. I have two questions regarding this: Is it possible to integrate the SBE protocol with grpc instead of protobuf? Are there res ...

Is there a JavaScript method for opening a new window regardless of the PHP file being used?

I have encountered a small dilemma that is causing me frustration. Currently, I have set up a BUTTON on my website. This button, when clicked, triggers a JavaScript function to open a "New Window". The code for this button and function looks like this : ...

Spinning item using a randomized matrix in Three.js

I'm in the process of creating a 3D die using Three.js that will rotate randomly when clicked, but I'm struggling to update the axis values properly. Here's where I'm currently at: <style type="text/css" media="screen"> html, ...

Is it possible to obtain the vertex coordinates of an aframe box?

Is there a way to extract the vertex from an object (specifically a box) in AFRAME, or calculate the intersection between a raycaster and an entity's face? Any assistance would be greatly appreciated. Thank you! EDIT: I have included the code snippet ...

Stylish CSS design for enhancing the appearance of grip boxes

Using CSS, I am trying to create a unique "grip" background that signifies an element is draggable. You can refer to this link: Currently, I have assigned a class called dnd to the item, and my CSS code looks like this: .dnd { background: #99bbee; /* lo ...

Arranging nested columns in a different order for smaller devices with Bootstrap 4

I am currently in the process of developing an e-commerce section, which includes an aside containing filters and a "main" section that should have 6 items displayed as individual cards. The challenge arises when viewing this on mobile screens, where the a ...

Steps for rearranging the order of CSS grid layout

Could you assist me in implementing a grid layout that fulfills these specific criteria? I'm unsure of how to proceed, so any guidance would be greatly appreciated. https://i.sstatic.net/vBtXc.png When there are more than 9 items, the current layout ...

Executing a JavaScript function during page load in an ASP.NET application

Similar Question: Javascript code to run after page has loaded In my ASP.NET 4.0 application, I am using JavaScript to show the client's time zone offset in a text box:- ` <script type="text/javascript"> function GetTimeZoneOffset() { ...

Tips for retrieving all error messages within a script tag using Vee Validate Version 4 in Vue 3

I am currently working with Vue 3 and vee-validate V4, but I'm facing an issue where I can't retrieve all error messages within the script tag. Is there a way to access all error messages from the script tag? <Form v-slot="{ errors }" ...

Determine the number of lines present in a textarea

Is there a way to use JavaScript to determine the number of lines in a textarea without relying on the rows attribute? For example, in this scenario, I would expect to get 4 lines. <textarea rows="4">Long text here foo bar lorem ipsum Long text he ...

Developing with Nuxt JS and WordPress API results in the error message: "Error accessing property 'title' of undefined"

I'm currently working on a website that utilizes the WordPress API for the backend and nuxt.js for the frontend. However, I am facing difficulties when it comes to displaying data on the frontend as I keep encountering the error message "Cannot read p ...

The Google Maps display for this page failed to load properly on the map

<!-- <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script> --> <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initialize" async="" defer="defer" type="text/javascript">& ...

"Implementing a toggle switch on your Odoo website the right way: a step-by

I am looking to implement a toggle switch in the header of my Odoo template. I came across this Bootstrap code snippet: <div class="custom-control custom-switch"> <input type="checkbox" class="custom-control-input" ...

Error encountered while trying to store a JSON object in local storage

When attempting to insert a JSON in localStorage, I am encountering the error Unexpected token ~ in JSON at position 3 during the parse process. Here is how I am inserting the data into localStorage: localStorage.setItem( "users", `"[\"~#iM& ...

Unveil concealed information within a freshly enlarged container

As I organize my content into an FAQ format, I want users to be able to click on a link and expand the section to reveal a list of items that can also be expanded individually. My goal is to have certain list items expand automatically when the FAQ section ...

A step-by-step guide to incorporating expandable and collapsible images within a div element using X

I have successfully created dynamic divs with some data that expand and collapse perfectly. Now I am looking to add expand and collapse images on these divs. I am relatively new to designing in xslt. <xsl:template match="category[key!='org.model.C ...