Trouble with Javascript file functioning correctly

I am currently working on a mini game project using HTML, CSS, and JavaScript.

Everything seems to be running smoothly with the HTML, CSS, and most of the JavaScript code. However, when I test the program in FireFox and attempt to click on a square div that matches the RGB value stored in a variable, it keeps giving the wrong answer. Instead of displaying "Correct" as expected, all the alerts are showing "Wrong".

This is the structure of the HTML file:

    <!DOCTYPE>  
 <html>
<head>
    <title>Color Game</title>
    <link rel="stylesheet" type="text/css" href="colorGame3.css">
</head>
    <body>

        <h1>
        RGB Color Game
        <span id = "colorDisplay">
        RGB
        </span>
        </h1>

        <div id="container">
            <div class="square"></div>
            <div class="square"></div>
            <div class="square"></div>
            <div class="square"></div>
            <div class="square"></div>
            <div class="square"></div>
        </div>

        <script type="text/javascript" src="colorGame3.js"></script>

    </body>
</html>

Here's how the CSS file looks:

    body{
    background-color: #232323;
    }

.square{
width:30%;
background:purple;
padding-bottom:30%;
float:left;
margin:1.66%;

 }

#container{

max-width:600px;
margin:20px auto;
}

This is what the JavaScript file contains:

    var colors = [
    "rgb(255,0,0)",
    "rgb(255,255,0)",
    "rgb(0,255,0)",
    "rgb(0,255,255)",
    "rgb(0,0,255)",
    "rgb(255,0,255)"
    ]

    var squares = document.querySelectorAll(".square");

     var pickedColor = colors[2];

    var colorDisplay = document.getElementById("colorDisplay");

      colorDisplay.textContent =  pickedColor;

      for(var i = 0; i<squares.length;i++){

squares[i].style.background = colors[i];

squares[i].addEventListener("click",function(){

var clickedColor = this.style.background;

    if(clickedColor === pickedColor){

        alert("Correct");

    }
    else{

        alert("Wrong");
    }
});
}

Answer №1

The colors selectedColor and chosenColor do not match, even though they both technically work in HTML. The code this.style.background; is adding a space between each color. They should be formatted like so...

var colorOptions = [
    "rgb(255, 0, 0)",
    "rgb(255, 255, 0)",
    "rgb(0, 255, 0)",
    "rgb(0, 255, 255)",
    "rgb(0, 0, 255)",
    "rgb(255, 0, 255)"
    ]

Answer №2

Your condition is not matching because of the space.

Here is the code for displaying an alert:

alert (pickedColor + clickedColor);
https://i.sstatic.net/bbKkl.png

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

Javascript: struggling with focus loss

Looking for a way to transform a navigation item into a search bar upon clicking, and revert back to its original state when the user clicks elsewhere. The morphing aspect is working correctly but I'm having trouble using 'blur' to trigger t ...

What is the best way to implement a shared function across two classes?

I have a jQuery code that works as intended with the .foto class. Now, I need to add the .fotoleft class to perform the same function. How can I make the function work for two different classes? $(document).ready(function() { $(".foto").click(functi ...

The curious case of looping and peculiar Vue actions

I've been working on a project where I am looking to dynamically add more input fields upon clicking a button. My initial attempt using jQuery.append ran into issues with detecting v-model. Switching gears, I decided to try achieving the same outcom ...

Hover over buttons for a Netflix-style effect

https://i.stack.imgur.com/7SxaL.gif Is there a way to create a hover effect similar to the one shown in the gif? Currently, I am able to zoom it on hover but how can I also incorporate buttons and other details when hovering over it? This is what I have ...

Achieving a scrolling body with a fixed header in a Vue b-table

Currently, I have implemented a b-table element on a webpage to display data from a database. The table is paginated, but feedback suggests that users prefer all information displayed in a single scrolling view. However, the issue arises when I attempt to ...

Transferring JSON data using $.post in Express/NodeJS

Below is the contents of my app.js file: var express = require('express'); var app = express(); var path = require('path'); var $ = require('jquery'); var nodemailer = require('nodemailer'); app.use('/static&a ...

How can I transform an array of text into dropdown options?

Currently, while utilizing Vue and vue-bootstrap, I am facing the task of populating a dropdown menu with an array of text items retrieved from my database. The <b-form-select> component in Bootstrap requires objects of the form {value: 'some va ...

Issue with Media Queries for adjusting width not functioning correctly

I'm currently working on a JavaScript calculator project and I'm having trouble making it responsive. Specifically, when the screen size decreases, the buttons in the calculator are not displaying properly, especially the operator buttons. I woul ...

Adjust the white background to match the gray background seamlessly

I'm in the process of developing a forum and encountering some challenges with CSS. My goal is to extend the white area all the way to the right edge of the gray background, leaving a gap of around 5px/10px. I've experimented with different CSS ...

Striped artifacts can be observed in the lights of A-Frame technology, with their appearance varying depending

I'm currently using A-Frame version 1.0.4 and have experimented with both spotlights (as shown in the attached image) and direct light sources. Adjusting the shadowBias to -0.0001 only minimally impacts the artifact issue. By setting shadowMapHeight ...

Working with AngularJS: How to sort ng-options when dealing with an object

Is there a way to sort the choices in a {select} like this? <select ng-options="value as name for (value,name) in vm.options" ng-model="vm.selected"> If the object vm.options is being used and sorting by values is desired, how can it be achieved? ...

Strategies for managing callback responses within Ejs

I'm facing a challenge in my Node.js application where I need to execute an async function within Ejs code and display the result. Here's what I've attempted: <ul> <% setTimeout(function () { %> <% supplies = [1, 2, 3, 4]; %& ...

Can a JavaScript string be converted into a date format for insertion into a SQL database?

I'm currently developing a bot and facing an issue where I need to make it upload two dates. However, the arguments it can have are numbers within strings. For example, I have two strings '08222020' and '10282022,' which I need to ...

The controller in my template is not being passed by the $routeProvider

I attempted to dynamically load a template in Angular using ngRoute... However, I encountered an issue with the following code: (app.js route configuration) app.config(function($routeProvider) { $routeProvider.when("/password", { templateUrl ...

What is the method for altering the color of the webkit-slider-thumb using JavaScript?

I am looking to adjust the color of an input range using JavaScript instead of CSS. Can someone help me with this request? Current CSS Code: input[type='range']::-webkit-slider-thumb { -webkit-appearance: none; background: goldenrod !importa ...

AccessMediaStream - camera direction

My current setup involves using an Android tablet and GetUserMedia to capture images in my program. It seems that by default, GetUserMedia uses the front camera. How can I set the rear camera as the default instead? Below is the code snippet I am using w ...

Gitbook is facing a unique challenge with the Chinese language in its HTML code - an issue with excessive spacing

Currently, I am utilizing gitbook and github pages to construct my personal webpage with the main language being Chinese. However, I have noticed that gitbook is adding an extra space in some places where it is unnecessary. Below is the text found in the m ...

Can React components be saved in an array?

I am currently working on enhancing the code snippet provided below. This code is intended to iterate through elements of an array using keys to locate images within a lengthy SVG file directly embedded in the document under the identifier "SomelongUglySVG ...

Having trouble updating the route with the $location service, even after attempting to use $scope.apply

After trying to utilize the location service with no success, I am left wondering why my view isn't changing even after using either $scope.$apply() or $scope.apply. Prior to posting my question, I conducted thorough research on similar inquiries but ...

How can I retrieve the latest state of the Redux store in getServerSideProps in Next.js?

I am attempting to retrieve the most up-to-date redux state in getServerSideProps like so: export const getServerSideProps = async (ctx) => { const state = store.getState(); console.log(state.name); return { props: { login: false } }; }; H ...