Employing jQuery's CSS method

As someone who is new to coding, I decided to create a basic color game using jQuery. The idea is simple - there are 4 options, you click the correct one, and an alert appears. I stored the answer along with some dummy colors in an array called "colors[]" and used that array to set the CSS for each color box.


var dummy = '#ccc';
var answer = '#ff9900';

var colors = [dummy,answer,dummy,dummy];

for (var i = 1; i <= 4; i++) {
  $('#colorBox'+i).css('background', ''+colors[i-1]+'');
}

$('#colorBox'+i).click(function() {
  if ($(this).css('background', ''+colors[answer]+'') == true) {
    alert("Congratulations!");
  }

However, I'm struggling to properly define the answer for the click function to work correctly. Any help would be greatly appreciated. Thank you.

Answer №1

After reviewing your code, I have identified a few key issues that need to be resolved.

  • Ensure to use the getter method for css() in the conditional statement and compare it directly to the answer string, as referencing colors[answer] is not valid.
  • Avoid repeatedly appending empty strings, as this can impact performance unnecessarily.
  • Move the click handler code inside the loop so that it properly interacts with the i variable.

However, the major flaw in your logic lies in assuming that all browsers return CSS colors in the same format, whether hexadecimal or RGB. This inconsistency could lead to errors in color comparison.

A more effective solution would involve applying classes to elements for easier identification of the correct answer. By grouping common elements under single classes instead of using incremental id attributes, you can streamline your code. Consider the following revised approach:

var classes = ['d', 'a', 'd', 'd'];
var $container = $('.container');

var html = '';
for (var i = 0; i < classes.length; i++) {
html += '<div class="colorbox ' + classes[i] + '"></div>';
}
$container.append(html).on('click', '.colorbox', function() {
    if ($(this).hasClass('a')) {
        alert("Congratulations!");
    }
});
.colorbox {
    width: 50px;
    height: 50px;
    border: 1px solid #000;
}
.colorbox.a {
    background-color: #ee00aa;
}
.colorbox.d {
    background-color: #aaa;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></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

In Chrome, there is a single pixel missing below the <dl> element

While my website's basic list looks great on Firefox and IE, there seems to be one missing pixel line in Chrome. Check out this JsFiddle link shared by Jared in the comments for reference. If you're not seeing the missing line, try adjusting th ...

Accelerating the Jquery/Json query速

Working with javascript/jquery for the first time has been quite a learning experience. I had to follow each step carefully, but I finally managed to get it working exactly how I wanted. My JSON file contains data formatted like this: [ { "Procedure ...

Assign a value to an input element with JavaScript and retrieve the value using PHP

Below is a form and input element that can be found in the cart.php file: <form id="cartform" action="cart.php?action=update&pd=<?php echo $row['product_id'] ?>" name="form1" method="post"> <?php $query = "select * from ca ...

The POST request in Node.js using Express is returning an undefined value

Having an issue with Node.js + express on the backend while trying to parse the body of a simple POST-request. The server console is showing "undefined" as the result. Tried various options from StackOverflow without success, even after including body-par ...

If the header 1 contains a specific word in jQuery, then carry out an action

I have successfully used the contains() function before, but I've never incorporated it into an if-statement. The code below doesn't seem to be working as expected. Essentially, I want to check if H1 contains the word "true" and perform a certain ...

Tips for avoiding whitespace in flexbox as you resize an item

My flex box setup is pretty straightforward: main { width: 660px; height: 100%; display: flex; justify-content: center; align-items: center; flex-direction: column; } When I look at my page, it appears like this: https://i.sstatic.net/JF8KC.j ...

Real-time Facebook updates without the need to refresh the page, allowing for seamless interactions with comments and

I am working on developing a social networking platform using ASP.net. One of the key features I need to implement is updating individual posts with new likes, comments, and posted time - similar to how Facebook operates. In addition, I want to incorporat ...

I am encountering issues where my PHP code is not functioning properly within the HTML script tag

Hey there, I have created a PHP file with two methods: 1) function restart(){ echo('restart') }; 2) function shutdown(){echo ('shutdown')}; Next, I included the index.php file in foo.php. However, when attempting to call the methods ...

Tips for navigating through webpage links, ensuring successful redirection and error handling in Selenium

I have attempted the code below to verify all links open successfully without any 404 errors: public void checkAllLinks() { suites.setupEnvironment(); WebDriver driver = suites.getWebDriver(); driver.get(suites.WEB_PATH5); ...

Search for "conditions" in a basic HTML DOM parser

I encountered an issue when trying to parse information from a website using simple HTML DOM parser. My code looks something like this: <li> <p class="x"></p><p>..</p> <p>..</p> <p>..</p> <p class ...

Can anyone explain why I am having trouble loading JavaScript files into a different HTML file?

Currently, I am developing an electron application. In my index.html file, I have successfully loaded JavaScript files in the head tag and can access the JS functions without any problems. Now, I have created a separate browser window with another HTML fi ...

The lists Ul and Ol are currently not displaying numbers or circles

Hi there, I'm encountering an issue with the ol and ul tags not displaying numbers and circles on the left side. I am not using a reset css file. Below is my code snippet: <ol> <li>ALL FILES</li> <li>PHP SCRIPTS</li ...

Is there a way to change a string that says "False" into a Boolean value representing false?

When retrieving values from the backend, I am receiving them as strings 'True' and 'False'. I have been attempting to convert these values into actual Boolean values, however, my current method always returns true. What is the correct a ...

Showing hexadecimal SQL values using PHP in an HTML form

I need assistance with dynamically loading a form that will display data from a SQL database. The data includes a hex color, name, and price. I want the user to see the color and name in the form, and upon submission, send the corresponding price. I have b ...

Having trouble displaying the fancybox helper buttons

I had everything working perfectly, but suddenly it stopped and I can't figure out what went wrong. I just need the left, right arrows, and helper buttons to appear when fancybox is open. Any assistance would be greatly appreciated. PS: All the neces ...

Column alignment issue detected

Can you help me with aligning the data in my column status properly? Whenever I update the data, it doesn't align correctly as shown in the first image. https://i.stack.imgur.com/300Qt.png https://i.stack.imgur.com/4Dcyw.png $('#btn_edit' ...

A guide to programmatically downloading a file with JavaScript on Internet Explorer

I'm currently facing a challenge with my web page. There is a button that, when clicked, should generate a CSV file (by converting from JSON) for the user to download. I've implemented the logic based on this jsfiddle, and it works perfectly in C ...

Trapping an iframe refresh event using jQuery

I am trying to dynamically load an iframe using jQuery. Here is my code: jQuery('<iframe id="myFrame" src="iframesrc.php"></iframe>').load(function(){ // do something when loaded }).prependTo("#myDiv"); Now, I need to capture th ...

Is the ajax request failing to execute in a synchronous manner?

I've encountered an issue with the following code snippet: let channels = ["freecodecamp","test_channel","ESL_SC2"]; channels.map(function(channel) { function genUrl(type, name) { return 'https://wind-bow.gomix.me/twitch-api/&a ...

Is there a way to eliminate the bottom padding in a textarea field?

Need help removing the bottom padding in a textarea? Check out this code snippet: $('textarea').css("height", $("textarea").prop("scrollHeight")) textarea { width: 300px; resize: none; margin: 0; padding: 0; } <script src="https://a ...