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

What is the best way to make an image expand when clicked, align it in the center of the webpage, and have it return to its original position with just one more click by utilizing

Currently, this is the code I am working with. The JavaScript functionality is working well, however, there seems to be an issue where the image does not return to its original size on a second click. Additionally, I am having trouble getting the CSS to ce ...

Exploring ways to connect my React application with a node backend on the local network?

On my MacBook, I developed a react app that I access at http://localhost:3000. In addition, I have a nodejs express mysql server running on http://localhost:5000. The issue arises when I try to open the IP address with port 3000 in the browser of my Window ...

Stylized widget for showcasing a list of cities for meetups

After extensive searching, I have yet to find a solution to stylize the "City List" widget for Meetup. The specific widget I am focusing on is the first one listed here. () Despite exploring various options such as the widget foundry and conducting onlin ...

I'm wondering why using display flex with justify-content center and align-items center is not properly centering the elements both horizontally and vertically. Can anyone explain this?

As I delve into the world of JavaScript, I find myself coding simple JS, HTML, and CSS snippets to enhance my learning experience. These exercises help me grasp the concepts well enough to create various JS web elements and projects. My goal is to eventual ...

Consolidating various JavaScript events into one single event

Whenever a user types a key, my function is triggered. I want to consolidate these events so they only occur at a maximum rate of 500ms. Is there a simple method to achieve this in Javascript or through a commonly used library? Or should I create my own t ...

What are some effective methods for overriding materialui styles?

Here is the CSS style for a checkbox in Material-UI that I captured from the console: .MuiCheckbox-colorPrimary-262.MuiCheckbox-checked-260 I attempted to override this style using the following code, but it was unsuccessful: MuiCheckBox: { colorP ...

Eliminate the jQuery AJAX timestamp from the URL parameters

Is there a way to eliminate the jQuery AJAX cache buster code (_=3452345235) from string URLs? While working on a global AJAX fail handler, I need to identify which URL failed. However, every time I locate the failed request's URL, the jQuery cache q ...

Simple steps to convert Redux state to Redux Persist with the help of 'combineReducers' function

I'm facing a challenge trying to implement Redux-Persist with my Redux state, particularly because I am using combineReducers. Here is the structure of my store: import { createStore, combineReducers } from 'redux' import { usersReducer } fr ...

Unable to modify page property status through the Notion API

I've been attempting to use the Notion JS-sdk to update a page's status using their API. However, I've run into some issues that I can't seem to resolve. Updating the status requires modifying the properties object, but no matter what ...

FixPermissions not working properly | Discord.js EXPERT

I am currently in the process of updating my bot to be compatible with the latest version of discord.js. I have successfully made various changes, but I am facing an issue with the overwritePermissions section within my ticket command. For some reason, the ...

What is the best way to adjust the Directions route Polyline to the edge of the map canvas?

I am currently working on a project that involves direction mapping, and I need the directions to be displayed on the right side of the panel when rendered. Here is what I am currently getting: However, I do not want the directions to appear behind the pa ...

Error: Unable to access the 'create' property of an undefined object while utilizing sequelize to register a user and add an entry

Whenever I try to execute this controller, an issue arises indicating a problem with the recognition of the .create method from the model. What is the correct way to import Sequelize in order to utilize it effectively? const db = require("../Models/m_use ...

3D Animation for All Browsers

I'm currently working on creating a small browser-based game and I've been experimenting with animations to get the desired effect. So far, the animation works well in Opera and Edge, although there is a slight cropping issue in Edge. Unfortunat ...

Node.js: Extracting parameters from the URL

When working with Rails, I make a POST request to my server: response = Typhoeus::Request.post("http://url.localtunnel.com/request?from=ola&to=ole") result = JSON.parse(response.body) Now in my Node.js application, I need to retrieve values for From ...

Is Kendo Telerik grid capable of applying conditional formatting while filtering?

Is it feasible to modify the background color of rows in a Kendo Telerik grid when a filter is implemented within an ASP.NET MVC application? ...

Incorporating the Material UI App Bar alongside React Router for an enhanced user

For my web development course project, I am venturing into the world of JavaScript and React to create a website. Utilizing Material UI's appbar for my header design, I have successfully incorporated react router to enable navigation on my site. Howev ...

Set the webpage to a fixed width

Is there a way to make my webpage fixed-width instead of liquid? I've tried changing the container size to pixels but the text still collapses when I resize the browser. Any suggestions on how to keep it at a fixed width? <!DOCTYPE html PUBLIC "-/ ...

Is there a way for me to configure my website so that when a link is clicked, my PDF file will automatically open in Adobe

I've been facing an issue where I need my users to access a specific PDF file from a link on my website. Currently, the PDF opens in a separate tab next to my site, but ideally, I would like it to be forced to open in Adobe Reader directly. Is this ac ...

What sets apart the <img> and <Image> layout attributes in NextJS?

While working on custom checkboxes, I came across a unique situation - the only way the positioning of the checkboxes aligns properly is if the classes '.init' and '.hover' are assigned to images, and the class '.done' is disp ...

The function this.$set is failing to update an array in VueJS

I am facing an issue where the console log shows me the updated array xyz, but when I try to print it in the DOM using {{xyz}}, it does not update. Can anyone shed some light on why this might be happening? data() { return { xyz: [] } }, met ...