Creating a Black Jack game using JavaScript document.write

I am currently in the process of developing a blackjack game using javascript. As of now, I have successfully implemented the dealer's and player's cards. However, when the player decides to draw another card, an issue arises. It seems that the document.write function is lagging behind in writing the required text on the webpage.

while (totalP < 21)
    {
        r = confirm("Hit?");
        if (r==true)
        {
            document.write("<center><br>You chose to hit. </center>");
            p[counter] = deck[Math.floor(Math.random() * deck.length)];
            document.write("<center><br>" + x + "'s next card: " + p[counter] + "</center>");
            totalP = total(p, totalP);
            if (totalP > 21)
            {
                for (var i=0; i<p.length; i++)
                {
                    value = p[i].substring(0,p[i].length-1);
                    if (value == "A")
                    {
                        totalP = totalP - 10;
                        break;
                    }
                    else if (i == p.length - 1)
                    {
                        document.write("<center><br>You busted. Total = " + totalP + " > 21. Dealer Wins!</center>");
                        break;
                    }
                }
            }
        }

Although the text "You chose to hit." does appear, the subsequent card information fails to display on the webpage after confirming the action. The confirm dialog box showing "You chose to hit." reappears until the player's hand exceeds 21.

If anyone can provide assistance with this issue, it would be greatly appreciated. Despite my efforts in researching online and troubleshooting independently, I suspect that the unreliability and slowness of the document.write function might be causing the problem compared to other sections of JavaScript code.

Answer №1

Avoid using document.write because it completely replaces the content of the document.

Instead, create an HTML document with various HTML elements where you can insert text.

You can target HTML nodes by their id attribute. For example, if you have a div like this:

<div id="myDiv"></div>

You can then use

var div = document.getElementById("myDiv");

to reference that div in your JavaScript code. You can update the text of that div using

div.innerHTML = "Hello World!";

You can also generate new HTML elements in this manner:

var newDiv = document.createElement("div");
newDiv.innerHTML = "I am a newly created div!";
var oldDiv = document.getElementById("myDiv");
oldDiv.appendChild(newDiv);

After implementing these changes, your HTML document will be updated to:

<div id="myDiv">Hello World!<div>I am a newly created div!</div></div>

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

React developer server is failing to automatically refresh the code

I've encountered an issue with react-dev-server where changes I make to the code do not reflect on the app itself even after refreshing (not hot-loading). I've tried setting up my own project as well as using Facebook's Create-react-app, whi ...

Can you provide the proper syntax for the Jquery done() function?

I'm currently dealing with the code below: However, I encountered an error on line 6: Uncaught SyntaxError: Unexpected token { Even after reviewing the documentation for the done() function, I'm unable to identify my mistake here. ...

React Data Filtering Techniques

I'm currently facing an issue with the if statement in my Action component. I'm struggling to figure out how to handle the case when an item is not found in the data from a JSON file. I have a Filtering function in a Context that I am using globa ...

Exploring the Functionality of Chaining in JQuery and Understanding its Inner Workings

I have a question and I am looking for the best answer. Hopefully, someone in our group can provide it. Most of you are familiar with jQuery chaining. It allows us to attach multiple events to an HTML element using just one statement. For example: $(&ap ...

Unable to establish a connection to localhost using Javascript due to net::ERR_CONNECTION_REFUSED error

My setup includes a node.js express server running my API on port 7070 and a Flask server hosting my webpage on port 5000. While I can successfully access my API from the server using curl with curl http://localhost:7070/latest, I encounter issues when try ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

Apply a CSS class to the initial item in each carousel present on a webpage

I am utilizing Bootstrap 4's carousel to showcase dynamic content. The challenge lies in marking the first item of the carousel with the CSS class ".active". While it is typically added directly in the HTML, it becomes complicated when dealing with dy ...

"Adjusting Material UI Select Size - A Guide to Resizing Your

Struggling with getting Material UI selects to work properly with height and width using 'vh' and 'vw', as well as adjusting text size with 'vh'. The boxes have the correct size, but the label text is no longer centered due t ...

Are there any alternative methods for clearing form fields following a successful thunk dispatch in React?

When implementing a Post API call in Thunk, I dispatch a boolean success key for successful requests and an error message for errors. Now the goal is to clear form data upon success and display the error message upon an error. To achieve this, I utilize ...

The comparison between using multiple Vue.js instances and components, and implementing Ajax tabs

I am looking to incorporate ajax tabs using vue js. Each tab will need an ajax request to fetch both the template and data from an api. Here is an example of the tabs: <div id="tabs"> <ul class="nav nav-tabs"> <li class="active">& ...

Using discord.js to conveniently set up a guild along with channels that are equipped with custom

When Discord devs introduced this feature, I can't seem to wrap my head around how they intended Discord.GuildManager#create to function. How could they possibly have expected it to work with Discord.GuildCreateOptions#channels[0], for instance, { ...

What could be preventing this AJAX call from running correctly?

I am in the process of developing a website that provides users with a discount based on a promotional code they can input. It is important for me to verify the validity of the code in our database before allowing a new sign-up to proceed. Below is the AJA ...

What is the rationale behind TypeScript's decision to permit omission of "this" in a method?

The TypeScript code below compiles without errors: class Something { name: string; constructor() { name = "test"; } } Although this code compiles successfully, it mistakenly assumes that the `name` variable exists. However, when co ...

Node.js Axios Returns Bad Request with Status Code 400

I am currently facing an issue while trying to send the results of a nodejs query to an endpoint. Interestingly, I receive a successful response when using Postman with the correct parameters, but encounter errors when attempting to use axios. data: ' ...

Encountering an issue in next.js with dynamic routes: getting a TypeError because the property 'id' of 'router.query' cannot be destructured since it is undefined

I am working on creating a dynamic page in next.js based on the ID. Here is the basic structure of my project: File path: app/shop/[id]/page.tsx This is the code snippet: "use client" .... import { useEffect, useState } from 'react' ...

Using the getElementById function in javascript to modify CSS properties

Here is the setup I am working with: <div id="admin"> This element has the following style applied to it: display: none; I am attempting to change the display property when a button is pressed by defining and utilizing the following JavaScript co ...

Executing a JavaScript function at a specified interval

I am a beginner in the world of programming and javascript. What I aim to accomplish : Executing a JavaScript function on page load, specifically showVideo(). I would like this function to run for approximately 10 seconds before moving on to the next func ...

Can JSON values be multiplied together?

Can you assign the value of a key in JSON by using the result of multiplying/adding two variables, values, strings+number, or strings+strings? Is this feasible? For example: { "string": "600*"+40 } ...

Interested in using jQuery to trigger the f12 key press?

In my current project, I have successfully disabled the f12 and right click using jQuery. Here is the code snippet: $(document).keydown(function(event){ if(event.keyCode==123){ return false; } else if(event.ctrlKey && event.shiftKey && ...

Endless Invocation of Promise Functions in NodeJS

Searching for a way to endlessly call functions with promises. Experimented with 2 scenarios, one successful and the other not so much. The goal of the code that failed is to retrieve data from an API and store it in a database. Currently learning about p ...