1

lu.style.opacity = lu.style.opacity += 0.01;
This is part of my non-jquery fade in function for a page where i want to have a fadeIn feature but not jquery.
I'm putting an alert on the function to see what the opacity is, and every time it is 0.01, so why is it only being added on one time?

The function I use

function fadein(lu,time){
if (lu.style.opacity<1)
  {
    lu.style.opacity = parseFloat(lu.style.opacity, 10) + 0.01; //add 0.01 to the opacity
    setTimeout(function(){fadein(lu,time)},time/100) //sets a timeout to the fadeIn function every time/100 miliseconds
  } 
}
2
  • Add an alert before that code so that you can see what value it is originally. Commented Oct 1, 2013 at 18:32
  • 0 then 0.1 then 0.1 forever after Commented Oct 1, 2013 at 18:33

5 Answers 5

5

Opacity is a string. You are doing string concatentation when you add to it.

console.log(typeof lu.style.opacity);
// "string"

Make sure that you are adding numbers:

lu.style.opacity = parseFloat(lu.style.opacity) + 0.01;

In case parseFloat returns NaN, this may be helpful:

lu.style.opacity = (parseFloat(lu.style.opacity) || 0) + 0.01;

Now the reason why you were not seeing a value change is this:

lu.style.opacity;
// originally empty string: ''
lu.style.opacity += 0.01
// translates to: lu.style.opacity = '' + 0.01
// which equals '0.01' which is valid, but when you do it again:
lu.style.opacity += 0.01
// it is doing this: lu.style.opacity = '0.01' + 0.01
// which is: '0.010.01'
// which is an invalid value for that css style so it retains the previous value of '0.01'
Sign up to request clarification or add additional context in comments.

2 Comments

@user2751288 No thanks are required, but upvotes and accepts are always appreciated.
Particularly an accept, so the next person that comes looking knows this is the answer
1
  1. Opacity is a string.
  2. The syntax is wrong (that +=).

    lu.style.opacity = parseFloat(lu.style.opacity) + 0.01;

Comments

0

I think you meant either

lu.style.opacity += 0.01;

or

lu.style.opacity = lu.style.opacity + 0.01;

Comments

0

Throw it in a while loop to monitor your progression towards your target opacity:

var TARGET_OPACITY = 60.0;
while(lu.style.opacity < TARGET_OPACITY) {
    lu.style.opacity = parseFloat(lu.style.opacity, 10) + 0.01;
}

Comments

0

I think you are not adding up correctly

lu.style.opacity = parseFloat(lu.style.opacity) + 0.01;

as @Pointy commented, try putting alert before u add up and after you add up.

2 Comments

It's cleaner but this should give the same result.
@dystroy you are right mate. lu.style.opacity is string and he is trying to add float to string. i am editing my answer though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.