Why is Property CSS of Undefined Giving Error?

var random;
var squareArray = [$('#square1'),$('#square2'),$('#square3'),$('#square4')];
var randomOrder = [];
var i = 0;
var j = 0;

function computerPlays() {
    random = Math.floor(Math.random() * 4);
    randomOrder.push(random);
    makeSquareBlink();
    userPlays();
}

function makeSquareBlink() {
    setTimeout(function() {
        var randomSquare = squareArray[randomOrder[i]];
        randomSquare.css('opacity', '0.5');
        setTimeout(function() {
            randomSquare.css('opacity', '1');
        }, 300);
        i++;
        if (i < randomOrder.length) 
            makeSquareBlink();
    }, 500);
}

function userPlays() {
    $('#square1').on('click', function() {
        if (randomOrder[j] === 0) {
            $('#square1').css('opacity', '0.5');
            setTimeout(function() {
                $('#square1').css('opacity', '1');
            }, 300);
        }
        else {  
            $('#counter').text('!!');
            makeSquareBlink();
        }
    });
    $('#square2').on('click', function() {
        if (randomOrder[j] === 1) {
            $('#square2').css('opacity', '0.5');
            setTimeout(function() {
                $('#square2').css('opacity', '1');
            }, 300);
        }
        else {  
            $('#counter').text('!!');
            makeSquareBlink();
        }
    });
    $('#square3').on('click', function() {
        if (randomOrder[j] === 2) {
            $('#square3').css('opacity', '0.5');
            setTimeout(function() {
                $('#square3').css('opacity', '1');
            }, 300);
        }
        else {  
            $('#counter').text('!!');
            makeSquareBlink();
        }
    });
    $('#square4').on('click', function() {
        if (randomOrder[j] === 3) {
            $('#square4').css('opacity', '0.5');
            setTimeout(function() {
                $('#square4').css('opacity', '1');
            }, 300);
        }
        else {  
            $('#counter').text('!!');
            makeSquareBlink();
        }
    });
}

function reset() {
    randomOrder = [];
    i = 0;
}

$('button').click(function() {
    reset();
    computerPlays();
});

Is there a way to modify the CSS property of the randomSquare variable in the makeSquareBlink function? I have provided the full code now, but it is still not functioning as expected. Can anyone provide further assistance to help resolve this issue?

Answer №1

It seems that the main objective of this game is to accurately click on the same square as the computer did beforehand, right?

A issue with your current code arises when makeSquareBlink() increments i by one during the computer's turn. Subsequently, if the user selects the wrong square within makeSquareBlink(), the code attempts to access randomOrder[i], which actually refers to randomOrder[1]. This will result in a value of undefined being returned since randomOrder only contains one element at that point. Consequently, squareArray[randomOrder[1]] will yield undefined, leading to an error message for undefined.css(...).

To rectify this issue, you can modify your makeSquareBlink() method by adding a parameter:

function makeSquareBlink(p) {
    setTimeout(function() {
        var randomSquare = squareArray[randomOrder[p]];
        randomSquare.css('opacity', '0.5');
        setTimeout(function() {
            randomSquare.css('opacity', '1');
        }, 300);
        p++;
        if (p < randomOrder.length) 
            makeSquareBlink(p);
    }, 500);
}

Then, you should call it within computerPlays using i as the parameter and within userPlays using j. I haven't tested this solution thoroughly as I'd like you to figure out the rest on your own ;)

Additionally, reconsider how you are attaching event listeners inside userPlays(), as this action will add click listeners every time the method runs. It might be beneficial to explore using jQuery's one() method or refactor your code so that the click listeners are only attached once.

By the way, here's a helpful fiddle that aided me in debugging your code: https://jsfiddle.net/hm69ff0a/

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

Refresh Rails 4 instance variables seamlessly without reloading the page

Is there a method to update an instance variable in the view without refreshing the page? I'm using AJAX to post and create a new record. After creating the record, I want it to be added to the current instance variable. Let's say I have an act ...

Identifying the moment an external swf file has finished loading

My JavaScript code is responsible for loading external swf files by adding the "object" and "embed" tags after the page has finished loading. I am looking for a way to detect when the swf file has been fully loaded so that I can handle this event appropr ...

Tracking the Height of Hidden Elements During Page Resizing

I am currently attempting to determine the height of a hidden element after the page has been resized. More details can be found at this link: The script is able to successfully log the height upon page load, but when the page is resized, it goes back to ...

Search for text in multiple tables using jQuery and automatically trigger a button click event when the text is found

I am attempting to query certain tables and click a button within a cell of a specific table. Below is the code I am currently using: links[1].click(); iimPlayCode('WAIT SECONDS = 2') var compTabs = window.content.document.getElementById(' ...

Transforming API data into a particular type using Typescript

I am looking to extract only specific properties from a given object. Can TypeScript interfaces be used to iterate through the data and eliminate unnecessary properties? Sample data: [ 0: { "original_language" : "en", "t ...

What causes the container's height to remain unchanged despite changes in the height of its image content?

When I set the height of an image to 50%, its container's height remains the same instead of automatically adjusting. HTML: <section class="img-show"> <div class="img-container"> <ul> <li cla ...

Tips for sending an input file to an input file multiple times

As a developer, I am facing a challenge with a file input on my webpage. The client can add an image using this input, which then creates an img element through the DOM. However, I have only one file input and need to send multiple images to a file.php i ...

Express is having trouble providing data to React

Currently, I am delving into mastering the realms of React and Express. My ongoing project involves crafting a learning application that fetches data from MySQL and renders it visually for analysis. To kickstart this endeavor, I set up a basic express ser ...

"Exploring the relationship between Typescript and Angular: transforming variables within different

Ever since I made the switch from JavaScript to TypeScript (Version 2.1.5), I have been facing an issue with the code that filters date selection. Despite my efforts, I haven't been able to find a good fix for it yet. Here are the two date-pickers: F ...

Utilize the Material UI feature to call the function

How can I pass a function as a prop to my Material UI component if the function is undefined within the component? import React, { Component } from 'react'; import styled from 'styled-components'; import InputBase from '@material- ...

Issue with touchstart event not firing when using Rails 5 and jQuery

I am currently utilizing a Bourbon/Refills component called sliding_panel, which includes an on('click touchstart') event for my navigation menu. The event works correctly upon initial page load, but stops functioning after that. It uses toggleCl ...

What could be causing the absence of req.body data in a specific route in my Node JS application?

Hello, I am encountering an issue with my Node JS application: When attempting to authenticate, I am receiving an "undefined" value for "req.body.username" upon sending a POST request to that specific route. This problem seems to only occur on this parti ...

Creating a compact Swiper slider: reducing image size without sacrificing full window coverage!

Utilizing Swiper to craft a slider that occupies the entire window, with a slight margin for a bar-- no issues there. (https://i.sstatic.net/qcGBA.jpg) However, the image I placed in for the slide () appears to be excessively enlarged. Is there a way to ...

Creating a dynamic webpage with flexible design and interconnected containers using the Bootstrap framework

Creating a responsive layout with nested divs using Bootstrap Check out my HTML code below: <div class="container-fluid" style="height: 350px;"> <div class="row-fluid clearfix" style="height: 100%"> <div class="col-md-9 column" ...

Ways to effectively incorporate Bootstrap into Lit?

Currently, I am in the process of converting a website from Polymer to Lit. I have made good progress with it, but I have encountered a roadblock when it comes to styling. In order to simplify development and focus on functionality, I have been following t ...

Attempting to create a TypeScript + React component that can accept multiple types of props, but running into the issue where only the common prop is accessible

I am looking to create a component named Foo that can accept two different sets of props: Foo({a: 'a'}) Foo({a: 'a', b: 'b', c:'c'}) The prop {a: 'a'} is mandatory. These scenarios should be considered i ...

How can I display all categories in a Radar chart using amcharts 5

I'm currently using React with amcharts to generate a Radar chart. The data I have is structured as an array of objects like this: { category: 'Something', value: 5 }. There are a total of 12 items in the data set. However, when plotting t ...

Updating the KML data on Google Maps V3 for a fresh look

I recently updated a map from V2 to V3 and I am working on incorporating code to automatically refresh the KML data every 30 seconds. The goal is to update the map with the latest data and display a countdown until the next refresh. Here is an example of ...

What is the best way to execute a PHP query using JQuery and Ajax?

I need assistance with a two-column layout where the first column contains draggable words and the second column is dropabble, allowing words to be moved between columns. How can I save this transition in my database table effectively? Currently, I am uti ...

Is There a Lack of 'Contains' Support in JavaScript's ScriptEngine?

Below is some code that I am working with. ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); engine.eval("[1, 2, 3].contains(1)"); However, when I run the code, it throws the following e ...