LokeshT
LokeshT

Reputation: 46

Changing Opacity of Div With javascript timer

Hey guys the solution to this should be simple, but im having difficulty figuring out what's going on. I have a timerScript.js file that looks like this

//global variables
var timerInterval = null; // the timer that changes opacity every 0.1 seconds.      

function StartTimer() 
{

    //disable the button
    document.getElementById('startOpacityTimerButton').disabled=true;
    timerInterval = window.setInterval(ChangeOpacity(), 100);

}

function StopTimer() 
{
    window.clearInterval(timerInterval);
    timerInterval = 0;

}

function ChangeOpacity() 
{
    var object = document.getElementById('opacityZone');
    var currentOpacity  = (+object.style.opacity);
    var newOpacity = currentOpacity + 0.1;
    object.style.opacity = newOpacity;
    if(newOpacity == 1.0)
    {StopTimer();}
}

This is what my code is supposed to do

  1. Click button -> Calls StartTimer
  2. StartTimer -> Disables button, calls ChangeOpacity every 100 milliseconds.
  3. ChangeOpacity -> gets the div element(opacityZone), gets its current opacity, increments by 0.1 and checks if it is at max opacity in which case it calls StopTimer.
  4. StopTimer -> clears the timer.

This is what it does: Timer starts, changes opacity to 0.1, and just seems to stop!?!

I tried debugging with safari Web Inspector, but im not too sure what's going on, maybe one of you JavaScript experts can help me out (im a noob at js). Thanks!

Upvotes: 2

Views: 3972

Answers (6)

arman amirkamali
arman amirkamali

Reputation: 111

I had same problem and after so many time searching this is my solution:

instead of this line

 var currentOpacity  = (+object.style.opacity);
 var newOpacity = currentOpacity + 0.1;

you have to use this line:

let newOpacity = String(parseInt(window.getComputedStyle(Object).getPropertyValue('opacity'))+0.2))

for alternative answer you can do this (if you have a white background :) ):

      let  i =0 ;
      let interval = setInterval(()=>{
        i+=0.1
        Object.style.color = `rgba(0,0,0,${i})`;
   
      },1000)

      if(Object.style.color === 'rgba(0,0,0,1)')
        clearInterval(interval)
      console.log()

Upvotes: 0

LokeshT
LokeshT

Reputation: 46

Thanks guys, i'll take a look at the suggestions. Was just trying to do it with JavaScript for the purpose of learning the language, here are the JavaScript functions i came up with to solve the problem.

//global variables
var opacityIncreasing; //boolean to know if opacity is increasing or decreasing.
var animationInterval;//time in millseconds to do animation.    
var timerInterval;//the timer that changes opacity depending on interval.   
var object;//object we are doing the animation on.
var currentOpacity;//currentOpacity of object.
//var buttonMessage;//message to make object appear or dissapear depending on animation.

function init(elementName,rateOfAnimation)
{
    var object = document.getElementById(elementName);
    animationInterval = rateOfAnimation;
    currentOpacity = Truncate((+object.style.opacity),1);
    document.getElementById('messageContainer').innerHTML=currentOpacity;
    if (currentOpacity==0)
    {
        opacityIncreasing = true;
    }
    else 
    {
        opacityIncreasing = false;
    }

    StartTimer();

}

function StartTimer() 
{
    //disable the button
    document.getElementById('startOpacityTimerButton').disabled=true;
    timerInterval = window.setInterval(ChangeOpacity, animationInterval);

}

function StopTimer() 
{
    window.clearInterval(timerInterval);
    timerInterval = 0;
    //enable Button
    document.getElementById('startOpacityTimerButton').disabled=false;
}

function Truncate (number, digits) 
{
        var multiplier = Math.pow(10, digits),
        adjustedNum = number * multiplier,
        truncatedNum = Math[adjustedNum < 0 ? 'ceil' : 'floor'](adjustedNum);

    return truncatedNum / multiplier;
}

function ChangeOpacity() 
{
    var object = document.getElementById('opacityZone');
    var stringOpValue = "";
    if(opacityIncreasing)
    {

        currentOpacity += 1/10;
        stringOpValue = String(currentOpacity.toFixed(1)); 

        object.setAttribute("style","opacity:"+currentOpacity+"; -moz-opacity:"+currentOpacity+";");//  filter:alpha(opacity="++")");

        document.getElementById('messageContainer').innerHTML= stringOpValue;
        if(currentOpacity.toFixed(1) == 1.0)
        {
            document.getElementById('startOpacityTimerButton').value = "Disappear";
            StopTimer();
        }
    }
    else 
    {
        currentOpacity -= 1/10;
        stringOpValue = String(currentOpacity.toFixed(1)); 

        object.setAttribute("style","opacity:"+currentOpacity+"; -moz-opacity:"+currentOpacity+";");//  filter:alpha(opacity="++")");

        document.getElementById('messageContainer').innerHTML= stringOpValue;
        if(currentOpacity.toFixed(1) == 0.0)
        {
            document.getElementById('startOpacityTimerButton').value = "Appear";
            StopTimer();
        }


    }

}

This is the HTML and CSS

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="X-UA-Compatible" content="chrome=1">
        <meta charset="utf-8">

        <title>Opacity Test</title>
        <style>
            body
            {
                text-align: center; 
            }
            #opacityZone
            {
                width: 350px;
                height: 25px;
                background-color: #F50;
                text-align: center;
                margin:0 auto;
                margin-top: 10px;
                margin-bottom: 10px;
                padding-top: 5px;
                /*opacity number between 0.0 and 1.0*/
                opacity: 0.0;

            }
            #messageContainer
            {
                width: 100px;
                min-height: 100px;
                background-color:red;
                color: white;
                font-weight: bolder;
                font-size: 72px;
                text-align: center;
                margin:0 auto;
                padding-top: 10px;
            }
            .roundedContainer
            {
                -webkit-border-radius: 15px;
                -moz-border-radius: 15px;
                border-radius: 15px,15px,15px,15px;
            }

        </style>

    </head>

    <body>
        <h2>Opacity Test</h2>
        <form>
            <input type="button" id="startOpacityTimerButton" value="Appear" onclick="init('opacityZone',50);" />
        </form>
        <div id="opacityZone">Do you see me?</div>
        <p id="messageContainer" class="roundedContainer"></p>
    </body>

</html>

Upvotes: 1

Andrew Ice
Andrew Ice

Reputation: 841

What everyone else above has been saying I completely agree with. Just use CSS3 Animations to change the opacity of the button.

Simply use something along these lines:

@keyframes opacityChange{
  from {opacity: 0.1}
  to {opacity: 1}
}

You can also declare the timeframe in which the change would take place.

And add a class via javascript/jquery to your button. (class = "opacityChange") And when clicking on a new button be sure to remove that class, so that it can be reimplemented to the button later on.

However, to fix your particular problem. (If for some reason you can't use css3)

Simply add this to the Change Opacity function:

if(newOpacity == 1.0){
  StopTimer();
}else{
  ChangeOpacity();
}

Looking at how you have it set up, that should work, unless i'm looking over something.

Upvotes: 0

Maksym Kozlenko
Maksym Kozlenko

Reputation: 10363

Have you considered using CSS3 transition effects instead of making it using JavaScript? Performance wise it should be much better:

For example:

-webkit-transition: opacity 1s ease-in-out;
-moz-transition: opacity 1s ease-in-out;
-o-transition: opacity 1s ease-in-out;
transition: opacity 1s ease-in-out;

Upvotes: 0

Niels Keurentjes
Niels Keurentjes

Reputation: 41958

Your problem is here:

window.setInterval(ChangeOpacity(), 100);

Instead of passing a reference to the function, you're now executing it inline and scheduling its return value. Change it to:

window.setInterval(ChangeOpacity, 100);

Apart from that, you should really use CSS transitions for stuff like this.

Upvotes: 2

gp.
gp.

Reputation: 8225

pass a function reference to window.setInterval. so pass ChangeOpacity and not ChangeOpacity()

timerInterval = window.setInterval(ChangeOpacity, 100);

Upvotes: 0

Related Questions