I'm having trouble getting my CSS opacity to smoothly transition back to its original state of .5 using setTimeout(). What could be

I recently started learning JS, Jquery, and CSS.

My goal is to create a Simon Says style game. However, when I attempt to animate the computer to automatically light up the correct square, I faced some challenges.

To address this issue, I decided to start the colored squares with an opacity of 0.5. Each square has a unique ID, and when that ID matches the correct number, I use

$(this).css("opacity","1"); to make it brighter

Unfortunately, I am struggling to figure out how to get the square to automatically change back to 0.5

I attempted using a setTimeout() function to delay the change back. Even though the code delays, it doesn't revert back. I have tried using both an empty space and 0.5 as values

<!DOCTYPE html>
<html>
<head>
    <title>Matchy Matchy</title>
    <link rel="stylesheet" type="text/css" href="simonSays.css">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script>
</head>
<body>
    <h1>Match the Colors!</h1>
    <div id="banner">
        <button id="reset">Reset</button>
        <span id="level">Level:1</span>
    </div>
    <div id="container">
        <div class="square" id="1"></div>
        <div class="square" id="2"></div>
        <div class="square" id="3"></div>
        <div class="square" id="4"></div>
        <div class="square" id="5"></div>
        <div class="square" id="6"></div>
    </div>

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

</body>
</html>
body{
    background-color:black;
    margin:0;
}

h1{
    color:white;
    text-align: center;
    background-color:steelblue;
    margin:0;
}

#banner{
    background-color:white;
    margin:0;
    text-align: center;
}


#container{
    max-width: 600px;
    margin: 20px auto;
}

.square{
    background-color:pink;
    float:left;
    padding-bottom:30%;
    width:30%;
    margin:1.66%;
    opacity: 0.5;
    transition: opacity 0.5s;
    --webkit-transition: opacity 0.5s;
    --moz-transition: opacity 0.5s;
}

//variables
var level = 1;

//add event listeners for player use
//probably can make a class and use toggle to shorten code
$(".square").on("click",function(){
    $(this).css("opacity","1");
});
$(".square").on("mouseleave",function(){
   $(this).css("opacity",".5"); 
});

init();
doLevel(level); //test

function init(){
    //go through all squares and add a random color as background
    $(".square").each(function(i, obj){
        $(obj).css("backgroundColor", generateRandomColor());
    });
}

function doLevel(level){
    //get the colors to copy
    var pattern = selectColors(level);
    //showPattern(pattern);
    //test
    console.log(pattern[0]);
}


function generateRandomColor(){
    var color = "";
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);

    var color = "rgb(" + r + ", " + g + ", " + b + ")";
    return color;
}

function selectColors(amount){
    //declare array to hold values
    var order = [];
    //loop through amount
    for(var i = 0; i < amount; i++){
        order.push(Math.floor(Math.random() * 6 + 1));
    }

    return order;

}

function showPattern(pattern){
    //for each number in pattern,
    for(var i = 0; i < pattern.length; i++){
        //for each square on the screen
        $(".square").each(function(j,obj){
            var $this = $(this); //settimeout changes to global, so I am declaring locally here
            //if the ID is equal to the pattern number
            if(parseInt($(this).attr("id")) === parseInt(pattern[i])){
                //brighten
                console.log("light up");
                $(this).css("opacity","1");
                //dim
                setTimeout(function(){
                    console.log("changing back");
                    $this.css("opacity",".5");
                }, 3000);

            }
        })
    }
}

The opacity should revert back to 0.5 after a certain time, but it remains at 1. I'm puzzled as to why it's not changing back and would appreciate any insights or alternative approaches.

Thank you!

Answer №1

When using setTimeout, be cautious as it resets the this pointer to the global scope which can lead to issues. It is recommended to use the object in the each call to avoid any complications.

Also, remember that opacity is a numerical value and therefore does not require quotation marks when setting it.

$(document).ready(() => {
  $('.square').each((i, e) => {
    $(e).css('opacity', 1);
    setTimeout(() => {
      $(e).css('opacity', 0.5)
    }, 3000)
  });
});
.square{
  width: 50px;
  height: 50px;
  opacity: 0.5;
  background: #000;
  margin-bottom: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>

If you're looking for another fun option, consider using jQuery animate for your animations.

$(document).ready(() => {
  $('.square').each((i, e) => {
    $(e).css('opacity', 1).animate({
      opacity: 0.5
    }, 3000);
  });
});
.square{
  width: 50px;
  height: 50px;
  opacity: 0.5;
  background: #000;
  margin-bottom: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></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

Error: Cloudant encountered a problem processing your request

Why is my attempt to upload JSON objects into a Cloudant database resulting in a "400 bad request" error? pos = { 'lat': position.coords.latitude, 'long' : position.coords.longitude }; $.ajax({ type: "POST", ...

Having trouble scaling image with CSS, not reacting to size properties

I have little experience in web development, but a small business client has me working on their website while I handle other tasks for them. I've created a home page design that is almost ready to be turned into a template for the chosen CMS. Things ...

Text panels that expand and delve into expanding topics

When hovering over the top and bottom black space, a script will show or expand some text without any issues. However, hovering over the area where the text appears may cause a strange jumping effect as if it is quickly closing and then reopening. Check o ...

Get the package from a Lerna-managed monorepository using a git URL

Currently working on a project using yarn. The project has a dependency that is part of a larger monorepo managed by lerna. Despite the subpackage being updated, it has not been published yet and I require access to that unreleased code. Is there a method ...

What is the process for transferring image attributes to the server via a URL?

My data transmission process only involves sending data. Below is the data I send: export const cabin = { name: '001', maxCapacity: 2, regularPrice: 250, discount: 0, image: './cabins/cabin-001.jpg', description: ...

The content on Twitter Bootstrap remains consistent

While using Twitter Bootstrap modals for updating contacts, I encountered some issues. The modal consistently displays the information of the first contact, whereas when displaying the information outside the modal, everything appears correctly. <?php ...

Get access to the file upload field using ajax

I'm encountering an issue with accessing the file upload field //HTML <input type='file' name='images' id="images" multiple> ////////////////// $('.bt-add-com').click(function(){ var formdata = new For ...

Getting the most out of Nexmo with multiple websocket connections

I have integrated the code provided by Nexmo (shown below) into my server. However, I am facing an issue where if two callers ping my server, the binary data from the second caller also streams into the same websocket endpoint, resulting in two binary st ...

Learning the process of accessing a JSON file from a different directory

I am faced with a straightforward folder structure, it looks like this: project │ └───data │ file.json │ └───js test.js My goal is to access the content of file.json within the test.js file in order to perform some ...

Problem with padding in Firefox when using jQuery's css() methodInconsistent behavior with padding property in

It has come to my attention that Firefox (specifically v19.0.2) is encountering an issue with the jQuery css() function when attempting to retrieve an element's padding. While using .css('padding-left') seems to be a workaround, it would be ...

"Encountering a Dilemma in Resolving State using

Struggling to implement ui router for setting states post fetching pages from a database, I encountered an error each time I tried clicking on a sref-link. Below are snippets from app/app.js and app/index.html. angular.js:10467 Error: Could not resolve &a ...

NodeJS reports an invalid key length, while C# accepts the key length as valid

Currently, I am in the process of converting Rijndael decryption from C# to NodeJS. The Key (or Passphrase) being used is 13 characters long, while the IV used is 17 characters long. Note: The length choice for both Key and IV is beyond my control Disp ...

The received data object appears to be currently undefined

I am currently using MapBox to display multiple coordinates on a map, but I am encountering an issue where the longitude and latitude values in my return object are showing up as undefined. Could there be a missing configuration that is preventing the data ...

The socket.io-client could not be located on the running Node.js server

Setting up a fresh installation of Node, Express, and Socket.io on a Linux environment using npm. When attempting to run a sample from the official socket.io source, I encountered an error stating that the 'socket.io-client' module was not found ...

Encountering difficulties accessing XML file on server via anchor tag

I have an XML file on the server that I am attempting to open in a browser when the user clicks on a link. Below is how I have set up the link, but it is not opening the file: Code: <a title="View XML" href="file://///90.0.0.15/docmgmtandpub/PublishD ...

Tips for updating the state of an individual component in ReactJS without having to re-render the entire component

As a beginner in ReactJS, I am seeking guidance on how to modify the state of a specific component that was created within a Map function. Imagine I have a basic component named panels, with multiple panel-items. Each panel-item is essentially one componen ...

challenges with template inheritance: when one template takes precedence over another

I have encountered an issue with my two HTML templates, login.html and signup.html. Both of these files inherit from the base.html file, but there seems to be a problem where one file is overriding the title and content of the other. So when I visit /login ...

Ways to tidy HTML/XML code?

Upon receiving a web service response, the data appears as such: <text>&lt;span class="TitleServiceChange" &gt;Service Change&lt;/span&gt; &lt;span class="DateStyle"&gt; &amp;nbsp;Poste ...

Angular tutorial on splitting a JSON array

I am looking to extract a portion of a JSON array in Angular. The array looks like the one in the image below.https://i.stack.imgur.com/w0hqC.png Below is the code snippet: export class AppComponent { color: string = 'green'; public stocklis ...

Retrieving rows from a MySQL table that contain a specified BIGINT from an array parameter

I've encountered a problem with mysql while using serverless-mysql in TypeScript. It seems like my query might be incorrect. Here is how I am constructing the query: export default async function ExcuteQuery(query: any, values: any) { try { ...