Struggling to implement a Rock Paper Scissors game using HTML, CSS Bootstrap4, and JavaScript, specifically facing challenges in getting the function to select a new image

Recently, in my coding class, we were tasked with creating a program that would display images of dice and generate random numbers when the refresh button was clicked. To practice using querySelector and setAttribute, I decided to expand on the lesson by incorporating a rock-paper-scissors game into the program. Unfortunately, I have been facing difficulties getting my code to execute the functions responsible for displaying the corresponding images of paper, rock, or scissors based on randomNumber1 or randomNumber2. Despite trying to implement the code with both Bootstrap4 and plain JavaScript, I haven't been able to resolve the issue. Oddly enough, in a previous exercise where we implemented similar functionality for rolling dice using just JavaScript, CSS, and HTML5 without bootstrap, everything worked smoothly.

Initially, I attempted to write the code using Bootstrap4, and it seemed to function correctly until I introduced the logic for randomizing the dice rolls upon clicking refresh. When this didn't work, I switched to regular javascript but faced the same issue--the code wouldn't run as intended. After spending hours trying to troubleshoot, I've hit a dead end. Below are snippets of the code I wrote using Bootstrap4 initially, and then the revised version using only JavaScript.

First Attempt with Bootstrap 4


    <!-- css stylesheet -->
      <link rel="stylesheet" href="stylesPractice2.css">
      <!-- Google Fonts -->
      <link href="https://fonts.googleapis.com/css?family=Kalam:400,700" rel="stylesheet">
    </head>

    <body>
      <div class="container">

        <h1 class="header">Rock, Paper, Scissors</h1>
        <div class = "decision">
          <h2 class = "subtopic">Need to make a decision???</h2>
        </div>

        <div class = "players">
          <h2 class = "subtopic">Player 1</h2>
          <img class = "responsive img1" src = "images/rockPaperScissors3.png">
        </div>

        <div class="players">
          <h2 class = "subtopic">Player 2</h2>
          <img class = "responsive img2" src = "images/rockPaperScissors3.png">
        </div>

        <div class = "whoWins">
          <h2 class = "subtopic">And the winner is . . .</h2>
        </div>

      </div>

    <script src = "rockPaperScissors.js" charset = "utf-8"></script>

    </body>

JavaScript Code Snippet


    // FIRST PLAYER CREATE RANDOM NUMBER
    var randomNumber1 = (Math.floor(Math.random() * 3)) + 1;
    // SECOND PLAYER CREATE RANDOM NUMBER
    var randomNumber2 = Math.floor(Math.random() * 3) + 1;

    function images1() {
      if(randomNumber1 === 1) {
        document.querySelector(".img1").setAttribute("src", "images/rockPaperScissors1.png");
      }
      else if(randomNumber1 === 2) {
        document.querySelector(".img1").setAttribute("src", "images/rockPaperScissors2.png");
      }
      else if(randomNumber1 === 3) {
        document.querySelector(".img1").setAttribute("src", "images/rockPaperScissors3.png");
      }
    }

Despite putting in effort, I wasn't able to progress beyond this point due to image randomization issues.

Second Attempt Without Using Bootstrap


      <link rel="stylesheet" href="stylesPractice2.css">
      <!-- Google Fonts -->
      <link href="https://fonts.googleapis.com/css?family=Kalam:400,700" rel="stylesheet">
    </head>

    <body>
      <div class="container">

        <h1 class="header">Rock, Paper, Scissors</h1>
        <div class = "decision">
          <h2 class = "subtopic">Need to make a decision???</h2>
        </div>

        <div class = "players">
          <h2 class = "subtopic">Player 1</h2>
          <img class = "responsive img1" src = "images/rockPaperScissors3.png">
        </div>

        <div class="players">
          <h2 class = "subtopic">Player 2</h2>
          <img class = "responsive img2" src = "images/rockPaperScissors3.png">
        </div>

        <div class = "whoWins">
          <h2 class = "subtopic">And the winner is . . .</h2>
        </div>

      </div>

    <script src = "rockPaperScissors.js" charset = "utf-8"></script>

    </body>

Both versions reach the </html> tag at the end.

CSS Styling Section


    body {
      font-family: 'Kalam', cursive;
      background-color: #76fc23;
      color: #2357fc;
    }

    .container {
      width: 80%;
      margin: auto;
      text-align: center;
    }

    .title {
      margin-top: 4.0rem;
    }

    .header {
      font-weight: 700;
      font-size: 5rem;
      line-height: 1.5;
    }

    h2 {
      font-size: 3rem;
    }

    .players {
      display: inline-block;
      margin: 0 2rem 3rem 2rem;
    }

    .player1 {
      text-align: center;
      margin-bottom: 3rem;
    }

    .player2 {
      text-align: center;
      margin-bottom: 3rem;
    }

    .img {
      width: 100%;
      height: auto;
    }

Final Touches in JavaScript


      // FIRST PLAYER CREATE RANDOM NUMBER
      var randomNumber1 = Math.random();
      randomNumber1 = Math.random() * 6;
      randomNumber1 = (Math.floor(Math.random() * 6)) + 1;
      // SECOND PLAYER CREATE RANDOM NUMBER
      var randomNumber2 = Math.random();
      randomNumber2 = Math.random() * 6;
      randomNumber2 = Math.floor(Math.random() * 3) + 1;

    function images1() {
      if(randomNumber1 === 1) {
        document.querySelector(".img1").setAttribute("src", "images/rockPaperScissors1.png");
      }
      else if(randomNumber1 === 2) {
        document.querySelector(".img1").setAttribute("src", "images/rockPaperScissors2.png");
      }
      else{
        document.querySelector(".img1").setAttribute("src", "images/rockPaperScissors3.png");
      }
    }

    function images2() {
      if(randomNumber2 === 1) {
        document.querySelector(".img2").setAttribute("src", "images/rockPaperScissors1.png");
      }
      else if(randomNumber2 === 2) {
        document.querySelector(".img2").setAttribute("src", "images/rockPaperScissors2.png");
      }
      else{
        document.querySelector(".img2").setAttribute("src", "images/rockPaperScissors3.png");
      }
    }


    images1();
    images2();

The main challenge lies in getting the functions to update the images based on randomNumber1 and randomNumber2 when they equal 1, 2, or 3. QuerySelector and SetAttribute must be utilized for this task, which has proven to be trickier than anticipated.

Answer №1

Changing the src attribute of an image dynamically isn't possible because images are considered replaced elements. This means that an image is not directly part of the document, but rather an external resource that gets inserted into the document. Since the image doesn't really exist in the document itself, it cannot be swapped out.

To replace an existing image with a new one, you would need to create a new image using new Image() in your JavaScript code.

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

Gradually alter the content within the div while transitioning the background color

I'm working with a div that has the following CSS properties: #results { background: #dddada; color: 000000; cursor: pointer; } #results:hover { background: #3d91b8; color: #ffffff; } How can I smoothly change just the text inside this div, u ...

Using Sinon with Ember to create a Mock Server

I am looking to test my controller by making an ajax call to my backend using Jasmine and Sinon. To fake my backend server with Sinon, I attempted the following approach: describe("fake server", function() { var server; beforeEach(function() { this ...

What is the proper way to utilize a variable within the translate3d function?

Currently, I am developing my portfolio and working on a function in JavaScript called translate3d(0,10px,0). My question is, how can I use a variable instead of hardcoding the value 10px? I attempted to use translate3d(0,a,0) where 'a' is a vari ...

Node.js expressing caution about the use of backslashes in console logging statements

While this issue may not be considered crucial, I have observed an unexpected behavior when it comes to logging backslashes to the console. To verify the results, please try the following two examples in your terminal. I experimented with versions 0.10 an ...

Using a Material-UI component to activate a React Router Link

Currently, I am facing an issue while using material-ui components in react with react-router. The problem arises when I try to display list-items that double up as link elements but also have a submenu inside which should not activate the parent link. Unf ...

Where can I locate the Socket.IO server within the local area network (LAN)?

I am currently in the process of developing an application that facilitates connections between devices within the same network. In my design, any device can act as a server, and I aim for clients to automatically detect the server without requiring users ...

Alignment issue with text in Vuetify Datatables cells

I'm experimenting with Vuetify on my Laravel Vue application, and everything seems to be working fine except for the DataTables styles. The padding of the cells is not vertically center aligned as expected. Here's a screenshot Interestingly, the ...

Avoid HTML code injection in an ExtJS4 grid by properly escaping the href attribute

I am facing an issue with escaping HTML in my Extjs grid. I have used the following configuration : return Ext.String.htmlEncode(value); In the renderer of my column, this method works perfectly for simple HTML tags like h1, b, i, etc. However, if I in ...

Adding query strings to the end of a URL in order to redirect to a new destination

After successfully capturing a query string at the start of my survey with PHP syntax, I now have it stored in a variable. My next challenge is to redirect to a different URL at the end of the survey, while also including that same query string. For insta ...

Instructions for removing all entries from a DynamoDB table

I am facing a challenge with deleting multiple items from a DynamoDB table. While the documentation suggests dropping and recreating the whole table, I want to avoid this approach as my table was created using AWS Amplify and I don't want to risk disr ...

performing a request to Axios API with the inclusion of ${item} within the URL

I am having trouble with calling axios in Vuetify due to backticks and ${} within the URL. I believe I need to convert it into JSON format, but my attempts have been unsuccessful. Could you please provide an explanation? Here is the code snippet. Whenever ...

Adjusting the document root in an Apache site's directory

I have been working on my portfolio website and I want to showcase some past projects. There is one particular website that I developed in the past which is no longer live, but I have an archived version of it. I would like to be able to view this old site ...

Issue with VueJS instance: Unable to prevent default behavior of an event

Is there a way to disable form submission when the enter key is pressed? Take a look at the different methods I've attempted along with the code and demo example provided below. SEE PROBLEM DEMO HERE Intended outcome: When you focus on the input, pr ...

Is it possible to retrieve values from my model when working with Django Templates and incorporating them in the JavaScript header?

With Django, I have managed to successfully retrieve and display data from my model in the content section of the template. However, I am facing issues retrieving data from the model in the header section of the template. Below is the code --> view.py: ...

I need to find a way to properly test a recursive, async JavaScript function by utilizing fake timers

I've been working with a basic recursive function that performs as expected when run. To thoroughly test its operation at each stage, I want to utilize Sinon's fake timers. Unfortunately, it seems that the fake timers are only affecting the init ...

There is a lack of 'Access-Control-Allow-Origin' header, resulting in no access to the API

Having some trouble with the UK Parliament API, I keep encountering this error: XMLHttpRequest cannot load . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not a ...

Experiencing problems with npm and bower installations, along with deprecated modules while setting up angular-phonecat project

Trying to execute npm install in terminal while setting up angular-phonecat based on instructions from https://docs.angularjs.org/tutorial Encountering issues with deprecated modules and errors during the bower install phase. Seeking advice on how to upd ...

Python's web scraping with Selenium

I have encountered an issue while trying to extract data from an HTML table. Although I was able to successfully count the rows, the problem arises when I attempt to print the data as it ends up repeating the same row multiple times. Can someone please h ...

Node.js server encountering a cross-domain error

As a beginner exploring node.js, I am embarking on setting up my very first installation. In my server.js file, I am defining a new server with the following code: var app = require('http').createServer(handler), io = require('socket.io&a ...

Unable to alter fxFlex property within Component using "setAttribute('fxFlex', '25%')" does not function properly in Angular 6

Currently, I am utilizing the flexLayout module to create responsive divs in my Angular application. You can find more information about flexLayout at https://github.com/angular/flex-layout and also at https://alligator.io/angular/flex-layout/. const nav ...