user2751288
user2751288

Reputation: 188

Adding to opacity in javascript is not working properly

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
  } 
}

Upvotes: 1

Views: 580

Answers (5)

kzh
kzh

Reputation: 20598

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'

Upvotes: 5

Shreedhar
Shreedhar

Reputation: 5640

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.

Upvotes: 0

Bucket
Bucket

Reputation: 7521

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;
}

Upvotes: 0

Sanjo
Sanjo

Reputation: 1250

  1. Opacity is a string.
  2. The syntax is wrong (that +=).

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

Upvotes: 1

jcarpenter2
jcarpenter2

Reputation: 5458

I think you meant either

lu.style.opacity += 0.01;

or

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

Upvotes: 0

Related Questions