Transferring data from JavaScript to an HTML page

I'm currently developing a rock, paper, scissors game using HTML and JS.

Here is the link to the complete code (CSS, JS, HTML): http://jsfiddle.net/fJw4R/. You can also view the game with images here:

The functionality of the .math-module is working well, with the computer randomizing its choice when the player selects rock, paper, or scissors.

Now, I want to display a text string underneath the computer screen indicating whether the player wins or loses. I've started working on a function that looks like this:

function theWinnerIs(userChoice, computerChoice) {
    // code to determine winner
}

How can I easily display the result from this function in the index file? For example, showing 'YOU WIN!' or 'YOU LOSE!'.

Any help on this would be greatly appreciated. Thank you.

Answer №1

A more concise approach is available instead of using a block of if statements:

var choices = { rock: -1, paper: 0, scissors: 1 };
var score   = choices[userChoice] - choices[computerChoice];
score       = score - (score/2|0) * 3;

This method will output -1 if the user loses the round, 1 if they win, and 0 in the case of a draw.

You can easily display the output in any desired container by updating its innerHTML property:

var results = {
  '-1': 'YOU LOSE',
   '1': 'YOU WIN',
   '0': 'IT\'S A DRAW'   
};
var resultContainer = document.getElementById('result');
resultContainer.innerHTML = results[score];

Check out a brief demonstration to see these concepts in action.

Answer №2

It seems like you're looking to dynamically display text based on the output of your "theWinnerIs" method. One suggestion is to create a div element on your webpage and use JavaScript to update its content. There are multiple approaches you can take to achieve this.

To add a div to your page, you can include something like

<div id="output"></div>
. Then, you can update the text within this div using the following code:

var outputElement = document.getElementById("output");
outputElement.innerHTML = theWinnerIs(userChoice, computerChoice);

For a different perspective, you can view an updated version of your code. Keep in mind that raina77ow's solution may be more elegant.

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 is the best way to determine the total number of rows that include a specific value?

Using AngularJS, I have a table that is populated with data using the ng-repeat directive. Here is an example: http://jsfiddle.net/sso3ktz4/ I am looking for a way to determine the number of rows in the table that contain a specific value. For instance, ...

Is there a way to eliminate the bottom border on the active navigation tab?

Here's the information I've gathered: Below is a snippet of code that I have: .nav-tabs { border-bottom: 3px solid #3FA2F7 !important; } .nav-tabs .nav-link { color: #02194A; font-size: 13px; padding: 12.5px !important; } ...

How can we eliminate duplicate arrays of objects within a multi-dimensional array using ReactJS and JavaScript?

let galleryItems = [ {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', size: 91153, …}, {id: 1029, name: 'College-Annual-Day.jpg', ext: 'jpg', mime: 'image/jpeg', si ...

Error encountered during Bootstrap 4 SCSS compilation: Invalid US-ASCII character identified as "xE2"

Encountering difficulties when compiling certain bootstrap 4 modules (switching from beta3). Despite the fact that the issue can be resolved by adding @charset: 'UTF-8'; to the _hover.scss mixin partial (which is flagged as deprecated within the ...

Breaking the layout using recursive components in VueJS

I am currently facing an issue where I need to dynamically load components. However, when some of these components are loaded, they appear with faulty or missing CSS styles due to a problematic first div element after the template. Removing this DIV manual ...

Step-by-step guide on creating a draggable navigation bar:

I am encountering an issue creating a droppable menu. I am currently working on Menu 1 but struggling to figure out how to make the drop-down menus appear on the right side. <link href='http://fonts.googleapis.com/css?family=Oswald:300,400' r ...

Add a unique identifier to a table row in a jQuery/AJAX function without the need for a looping structure

My PHP query retrieves client data and generates a table with rows for each client. Each row contains a link with a unique ID attached to it. Clicking on this link triggers an AJAX function based on the client's ID, which opens a modal displaying info ...

Group records in MongoDB by either (id1, id2) or (id2, id1)

Creating a messaging system with MongoDB, I have designed the message schema as follows: Message Schema: { senderId: ObjectId, receiverId: ObjectId createdAt: Date } My goal is to showcase all message exchanges between a user and other users ...

Issue with mouseout gap in Microsoft Edge when using the <select> element

A noticeable gap appears in Microsoft Edge between the <select> menu and its options when expanding the menu, as shown here: https://i.stack.imgur.com/SprJ2.png This particular issue can cause problems with the mouseout event due to inconsistent be ...

TS2345: The argument provided, which is of type 'Event', cannot be assigned to the parameter expected, which is of type 'HtmlInputEvent'

I am facing an issue while trying to upload a file, and I could use some assistance in resolving it. Angular-----Error: src/app/admin/producto/create-producto-dialog.html:38:47 - error TS2345: Argument of type 'Event' is not assignable to parame ...

Enhanced customization of material-ui styles

After exploring various resources on styling overrides, I encountered a unique challenge. I am engaged in crafting styled material-ui components and integrating them across different sections of my application. My objective is to enable the customization o ...

Can someone provide guidance on utilizing parentheses in HTML code?

I am facing an issue in my Angular project while using the WordPress API. The problem lies in the API address structure which includes "" like this: <img src="{{importantvideo.better_featured_image.media_details.sizes.["covernews-med ...

Customizing the width of an <input> element in HTML/CSS

Despite receiving some feedback, the issue regarding width control of <input> remains unresolved. This particular problem pertains to a WordPress website, but can be replicated in a very basic manner. Situation: I have created a CSS nested heading/ ...

Storing user authentication tokens securely in session storage within Next.js can help maintain a

Is there a way to ensure that user data remains persistent even after a page refresh? I considered storing it in local storage, but that may result in a flash of unauthenticated content. Storing it in a cookie could also be problematic when working with ...

Setting a variable in Angular after a successful AJAX call

Working on a new small application and experimenting with Angular. Encountering an issue where I am making an AJAX GET request upon clicking a button. After receiving the response, I want to set a variable to hold the result, but for some reason the variab ...

What is the process by which Node can access predefined variables in clustering?

Consider the following code snippet: var running = false; var cluster = require('cluster'); if(cluster.isMaster){ cluster.fork(); running = true; } If this code is executed within multiple forks, would the value of 'running' ...

Utilize Set.Attribute prior to entering the for loop

Could someone please clarify why I am unable to declare the var node before the for loop and then simply use appendChild(node) inside the loop? Why is it necessary to declare it for each iteration in order for it to affect all div elements? Otherwise, it w ...

Navigating to a different page in the app following a document update: a step-by-step guide

I am facing an issue with a page where I am trying to print a specific DIV using the script below... function printReceiptDiv() { var divElements; if (vm.isDLR) { divElements = document.getElementById("DLRreportCont ...

The selected image should change its border color, while clicking on another image within the same div should deselect the previous image

https://i.sstatic.net/jp2VF.png I could really use some assistance! I've been working on Angular8 and I came across an image that shows how all the div elements are being selected when clicking on an image. Instead of just removing the border effect f ...

Applying a Webkit Scroll Bar to a specific element on the webpage

I've been attempting to apply the Scroll Bar webkit styling to a particular element but haven't had any success. Despite searching extensively, I have come across 2 threads on Stack Overflow that do not provide a solution. Most of the available ...