1

I've very new to javascript, and im having some weird issues. Im trying to fade out an image, note that the code for this is not yet complete. To my knowledge, this should work. but doesnt. Here's the code.

function changeimg() {
  var allElements = document.getElementsByClassName('picture');
  console.log(allElements.length);
  for (var i = 0; i<allElements.length;i++) {
    var opac = window.getComputedStyle(allElements[i]).opacity; 
    if (opac > 0.2) {
      fadeout(allElements[i]);
      break;
    }
  }
}

function fadeout(element) {
  console.log("reduce opacity");
  var opac2 = window.getComputedStyle(element).opacity; 
  element.style.opacity = opac2 - 0.05;
  if(opac2 > 0.2) {
    setTimeout(fadeout(element), 100);
  }     
}

This is meant to find the image that is now visible, and fade it out. this works, but it happens instantly. No matter what value i give to the setTimout() method, it never uses it, and completes it almost instanly.

I've looked around on the internet, and it seems i need to lose the () on my fadeout() method. But how then can i give the fadeout method the element which to fade out?

thanks in advance

  • 1
    Right, because `setTimeout` expects a function, not whatever your function returns, `undefined` in this case. Note that `f` is not the same as `f()`. – elclanrs Sep 29 '14 at 19:56
  • 3
    `setTimeout(function(){fadeout(element);}, 100);` – Igor Sep 29 '14 at 19:59
  • You may also want to know that `window.getComputedStyle(allElements[i]).opacity;` returns a string, not a number. – jfriend00 Sep 29 '14 at 20:04

1 Answers1

0

You are passing undefined to setTimeout, which expects a function. This is why you experience the behavior. You need to pass a function, read more here. The fixed code below should help.

function changeimg() {
  var allElements = document.getElementsByClassName('picture');
  console.log(allElements.length);
  for (var i = 0; i<allElements.length;i++) {
    var opac = window.getComputedStyle(allElements[i]).opacity; 
    if (opac > 0.2) {
      fadeout(allElements[i]);
      break;
    }
  }
}

function fadeout(element) {
  console.log("reduce opacity");
  var opac2 = window.getComputedStyle(element).opacity; 
  element.style.opacity = opac2 - 0.05;
  if(opac2 > 0.2) {
    setTimeout(function() {fadeout(element);), 100);
  }     
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175