Pawel Szewczyk
Pawel Szewczyk

Reputation: 21

Function called within a function not working

Im going to post it as I can not find the answer how to fix that.

I have the following code where I change background color for some divs. I have a function for that changeSqColor() which doesn't work when called within another function. What is the problem here? (array colors are defined and the number of elements = number of the divs)

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

function changeSqColor() {
    for (var i = 0; i < squares.length; i++) {
        squares[i].style.background = colors[i];
    }
}

changeSqColor(); // this works ok colors are changes

function resetGame() {
    //other commands
    changeSqColor(); //this one doesnt work, in console it says 'undefined'
}

Upvotes: 1

Views: 2189

Answers (3)

Pawel Szewczyk
Pawel Szewczyk

Reputation: 21

ok, i know what was the problem. i declared local variable as a new place for colors.

before

function resetGame (){
var colors = generateRandomColors(6);
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
messageDisplay.textContent = "";
changeSqColor();
}

after:

function resetGame (){
colors = generateRandomColors(6); // var removed
pickedColor = pickColor();
colorDisplay.textContent = pickedColor;
messageDisplay.textContent = "";
changeSqColor();
}

stupid mistake ;-)

Upvotes: 0

MukundK
MukundK

Reputation: 86

changeSqColor(); - This works because you are explicitly executing the method call by () brackets.

resetGame() you are just defining method by not executing it. if you want to define the function resetGame() as well execute it in one go, we can do it as,

(function resetGame() {
    //other commands
    changeSqColor(); //this one doesnt work, in console it says 'undefined'
})()

if you are calliing resetGame() method then 'undefined' will come if your function changeSqColor() is not in scope/accessible while resetGame() is getting executed.

Upvotes: 0

Manikant Gautam
Manikant Gautam

Reputation: 3581

You should have to call function resetGame sometimes in your code. You haven't invoked resetGame .

var squares = document.getElementsByClassName("square");
let colors = ['red','green','blue','white','yellowgreen'];
function changeSqColor() {
  for (var i = 0; i < squares.length; i++) {
     squares[i].style.background = colors[i]; 
   }
setTimeout(function(){resetGame();},3000);// call resetGame Function.
}
changeSqColor(); 

function resetGame (){
 for (var i = 0; i < squares.length; i++) {
  squares[i].style.background = colors[0]; 
  }
  setTimeout(function(){changeSqColor();},3000);
  // As you mentioned calling changeSqColor() 
}
<div class="square">1</div>
<div class="square">2</div>
<div class="square">3</div>
<div class="square">4</div>
<div class="square">5</div>

Upvotes: 1

Related Questions