Joey Smith Joey Smith - 6 months ago 17
Javascript Question

Trouble Setting Intervals with Jquery & a faulty function

I am writing a javascript document, using Jquery, where I am trying to cycle through an array of colors as my background while managing the alpha value separately. The "setColor" function works perfectly fine however the "manageAlpha" function does not seem to work at all. My goal is to set my alphaVar to the absolute value of a sin function in increasing increments of PI/10 with a .15 second interval. I cannot figure out this issue! Please help!

var backgroundCol = new Array(53);
var alphaVar;

backgroundCol[0] = 'rgba(255,192,192,' + alphaVar + ')';
//(array truncated)

var colorCounter = -1;
var numberOfColors = 53;
var colorTimer;
var alphaTimer;
var sinCounter = 0;
var goingUp = true;

function setColor() {

$('body.page1').css('background-color', (backgroundCol[colorCounter]));

colorCounter += 1;
if (colorCounter >= numberOfColors) {
colorCounter = -1;
}

}

function manageAlpha() {

sinCounter += Math.PI / 10;
alphaVar = abs(sin(sinCounter));
}

$(document).ready(function() {

$('body.page1').css('background-color', (backgroundCol[colorCounter]));

//colorTimer = setInterval(setColor, 150);
alphaTimer = setInterval(manageAlpha, 150);

});

Answer

First thing, in order to use use the absolute value and sin functions, use Math.abs() and Math.sin():

function manageAlpha() {
    sinCounter += Math.PI / 10;
    alphaVar = Math.abs(Math.sin(sinCounter));
}

Then, the other issue is that the values in the backgroundCol array will not update themselves automatically when alphaVar is changed. When you define

backgroundCol[0] = 'rgba(255,192,192,' + alphaVar + ')';

the value of alphaVar is undefined, so backgroundCol[0] is the string "rgba(255,192,192,undefined)", even if the value of alphaVar changes later.

What you can do is leave alpha out of the backgroundCol array and add it in when you call .css().

So something like:

backgroundCol[0] = 'rgba(255,192,192,';

function setColor() {
    $('body.page1').css('background-color', backgroundCol[colorCounter] + alphaVar + ')'); 
}
Comments