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

Tips on obtaining a Firebase ID

Does anyone have a solution for retrieving the unique id from Firebase? I've attempted using name(), name, key, and key() without any success. Although I can view the data, I'm struggling to find a way to retrieve the id. This information is cru ...

Struggling to comprehend the filtering arguments in VueJS?

While going through the VueJS Filter(orderby) API documentation, I came across some confusion regarding the arguments. Below is a sample for reference: Arguments: {String | Function} targetStringOrFunction "in" (optional delimiter) {String} [...s ...

Using JavaScript, append a hidden input field in Yii2 and retrieve it from the controller

Seeking assistance as a newcomer to yii2. I'm looking for help in resolving an issue that has arisen. I'm attempting to add a hidden input field to my form using JavaScript (not linked to a model). Subsequently, when I submit the form, I want to ...

What is the method to ensure that flexbox takes into account padding when making calculations?

There are two sets of rows displayed below. The first row contains two items with a flex value of 1 and one item with a flex value of 2. The second row contains two items with a flex value of 1. As per the specification, 1A + 1B = 2A However, when ...

Searching for a RegEx expression or jQuery selector that will exclude "external" links in the href attribute

I am using a custom jQuery plugin to enable Ajax loading of page content when certain links are clicked. Implementing this is straightforward with a delegated event like $(document).on('click','a', function(){});. However, I want this ...

Let's implement a sleek "load more" feature for your ASP.NET repeater just

Hey there, I was wondering if anyone has any cool samples of how to implement a Twitter-style load more items feature. How can I accomplish this using an ASP.NET repeater? ...

A guide on displaying data dynamically in Laravel with jQuery without the need for a page refresh

I am eager to fetch data from the database without having to reload the page. Currently, I am utilizing Laravel for this task and have been able to successfully retrieve the data using jQuery. Below is a snippet of my jQuery code: function fetchData() { ...

Issue with MVC 4 Asynchronous File Upload: Controller Always Receiving Null Value

I'm encountering an issue while attempting to upload a file asynchronously from ajax to my controller. I am passing 3 variables - PictureId, PictureName, and PictureFile. The problem specifically lies with the "PictureFile" variable as it consistently ...

unable to utilize the library three.js

I stumbled upon an interesting animation on Codepen that uses blocks to reconstruct a map image. The necessary JavaScript files are three.min.js and TweenMax.min.js. I copied the links from Codepen and pasted them into my HTML using <script src="">&l ...

Setting up a connection to MongoDB on a local network using express and mongoose

As I set up a server with express and mongoose, my goal is to make it accessible on other devices within my local network. To achieve this, I configured the bind_ip variable to 0.0.0.0 in the Mongodb configuration file. const connection = mongoose .co ...

Avoid production build warnings in Vue.js without the need to build the code

Experimenting with vuejs, I decided to use it for a simple page even though I could have achieved the same without any framework. Now, my project is nearly production ready. The only issue is that it's just a single js and html file, but it shows thi ...

React frontend communicating without backend server

Is it possible to send a message between two frontend users on web applications built with React? ...

Securing User Profiles in Firebase

I am currently working on a coding issue that involves the security of user profiles. While it doesn't involve sensitive information like payment details or personal data, it does pertain to the ownership of a profile. Currently, I store users' ...

Browser Compatibility in Three.js

Could someone assist me with activating webgl on Internet Explorer version 8? I am able to use Firefox and Chrome without any issues. Your help would be greatly appreciated. ...

Vue 3 - Using Emit Functionality in a Reusable and Composable File

I'm trying to utilize the emit function in my file called useGoo.ts import Swal from "sweetalert2/dist/sweetalert2.js"; export default function useModal() { const { emit } = getCurrentInstance(); function myId() { emit('id&ap ...

Adjust the width and height of the span to encompass more than just the content within it

I'm struggling to apply height and width to empty spans using CSS, but the span only fills its content <div class="container"> <div id="widgets-container"> <span class="widget" name="widget1" style="background-col ...

Issue with Internet Explorer: Refusing to run javascript included in AJAX-loaded content

While loading AJAX content that includes a javascript function using the jQuery .load function with done() on completion, I am facing an issue. $('#content').load(a, done); function done() { if(pagejs() == 'function') { ...

What strategies are typically employed to prevent falling into the callback hell trap when working with error-back asynchronous functions in Node.JS?

As a new Node user, I've been practicing pure Node scripting without relying on third-party npm packages. However, I quickly ran into the issue of my code becoming nested with callbacks inside callbacks, making it difficult to follow. This can lead to ...

Steps to Hide a Material-UI FilledInput

Trying to format a FilledInput Material-ui component to show currency using the following package: https://www.npmjs.com/package/react-currency-format Various attempts have been made, but none seem to be successful. A codesandbox showcasing the issue has ...

How can the output directory of the CSS file generated by Compass/Webby be modified?

I need assistance in getting my *.css file to be outputted in the output/css directory instead of the stylesheets directory. How can I achieve this? Here's what I've already attempted: Compass.configuration do |config| config.project_path = F ...