0

I am trying to teach myself a bit of Javascript and made this collection of divs that I am fading out at random intervals using jQuery as an experiment!

I would like to determine when each individual div's opacity is 0, so that I may fade them back in.

This is what I have so far

/*
  author: Tim Down
  source: http://stackoverflow.com/a/4257739/1252748
*/
function hasClass(el, cssClass) {

    return el.className && new RegExp("(^|\\s)" + cssClass + "(\\s|$)").test(el.className);

}

function checkVisibility(id) {

    console.log(id);
}


function timeFunction(current, element) {

    var elementId = element.id;

    /*
      author: Remy Sharp
      source: http://twitter.com/#!/rem/status/15427387974
    */
    var color = '#' + (~~ (Math.random() * 16777215)).toString(16);
    var border = '#' + (~~ (Math.random() * 16777215)).toString(16);

    console.log(color);

    $('#' + elementId).css("backgroundColor", color);
    $('#' + elementId).css("border", "1px solid " + border);

}


function randomFromInterval(from, to, qty) {

    /*
      author: Francisc
      source: http://stackoverflow.com/a/7228322/1252748
    */

    var arr = [];

    for (var i=0; i <= qty; i++) {
        arr[i] = Math.floor(Math.random() * (to - from + 1) + from);
    }

    return arr;
}



function getDelayArray(qty) {

    var from = 100;
    var to   = 10000;
    var delayArray = randomFromInterval(from, to, qty);

    return delayArray;

}




function filterUndefinedRecordsInArray(arr) {

    /*
      author: vsync
      source: http://stackoverflow.com/a/2843625/1252748
    */


    //arr = arr.filter(function(){return true});
    arr = arr.filter(Number);

    return arr;
}



//remove non-numbers
function only_numbers(str) {

    //remove non-numbers

    /*
      author: csj
      source: http://stackoverflow.com/a/1862219/1252748
    */

    str = str.replace(/\D/g,'');
    return str;

}

function getColors() {


    var colors = randomFromInterval(0, 255, 3);

    var r = colors[0];
    var g = colors[1];
    var b = colors[2];

    //random alpha
    var a = (Math.random()).toFixed(2);

    var c = {

        r: r,
        g: g,
        b: b,
        a: a,

    }

    return c;
}

$(document).ready(function() {


    var grid      = "";
    var idCounter = 0;
    var rows      = 15;
    var columns   = 15;
    for (var g = 1; g <= rows; g++) {

        grid += "<div class='break'>";

        for (var i = 1; i <= columns; i++) {

            var c = getColors();
            var b = getColors();
            grid += "<div id='div_" + idCounter + "' class='fl pixel' style='background-color:rgba(" + c.r + "," + c.g + "," + c.b + "," + c.a + "); border:2px solid rgba(" + b.r + "," + b.g + "," + b.b + "," + b.a + ")'></div>";

            idCounter++
        }

        grid += "<div class='cb'></div>";
        grid += "</div>";

    }

    $('body').append(grid);

    //how to distribute the fading times
    var delayArray = getDelayArray(15);
    //console.log(delayArray);

    var idArray = [];

    var elements = document.getElementsByTagName("div");

    var current = 0;

    while (current <= (elements.length - 1)) {

        var currentElement = elements[current];

        if (hasClass(elements[current], "pixel")) {

            //get the divs' ids but remove the "div_" from the beginning
            var cleanCurrentElementId = only_numbers(currentElement.id);

            //an array of the ids of all the divs with the class 'pixel'
            //but it still gets some elements filled with undefined as
            //it increments outside the if ( hasClass ) loop
            //so below it must have these undefined elements removed
            idArray[current] = cleanCurrentElementId;
        }
        current++;
    }

    //an array of all the ids of the divs on the page that have the 'pixel' class
    var cleanIdArray = filterUndefinedRecordsInArray(idArray);

    //randomly pick a quantity from the above array (cleanIdArray)
    //set from / to / qty variables so that the randomly chosen numbers
    //are within the range of the availble divs
    var from   = 1;
    var to     = cleanIdArray.length;
    var qty    = 250;
    var idsToFade = randomFromInterval(from, to, qty);


    for (var fadeId in idsToFade) {

        var tempId = idsToFade[fadeId];

        var delay = getDelayArray(1);

        $('#div_' + tempId).fadeTo(delay[0], 0);

        //checkVisibility($('#div_' + tempId).attr('id'));

    }


});

DEMO: http://jsfiddle.net/loren_hibbard/dZtFu/

But I do not know how to determine when each individual div has completed his fadeTo.

Although, when I fade them back in, I'd like to give them a random rgba value again; I understand jquery .css does not support that. Has anyone an idea on how I can give a new rgb and opacity value.

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
1252748
  • 14,597
  • 32
  • 109
  • 229

2 Answers2

2

Neat!

Give the fadeTo a callback as the third argument:

function giveRandomValue(){
    // Use your getColors() function here to set a new color and opacity

    // var color = ...;
    // $(this).css('background-color', color);
    // etc...
}

$('#div_' + tempId).fadeTo(delay[0], 0, giveRandomValue);

Documentation at jquery.com

Supr
  • 18,572
  • 3
  • 31
  • 36
  • Thanks! When I plug this in ( http://jsfiddle.net/loren_hibbard/jcyfG/ ), it works perfectly! – 1252748 Mar 22 '12 at 15:02
  • however, when I try to pass it the id of the element that's changing, it breaks. $('#div_' + tempId).fadeTo(delay[0], 0, giveRandomValue(tempId)); so that, function giveRandomValue(div){ var now = new Date() console.log(div) ; console.log(now); } returns the same exact time stamp for every div faded, whereas before, they were successive. http://jsfiddle.net/loren_hibbard/BfQfz/ – 1252748 Mar 22 '12 at 15:07
  • That's not how you use callbacks ;) You can't supply arguments like that, it will only accept the name of a function to call. That function will then be called with `this` set to the element which was being faded. Inside `giveRandomValue` you would then use `$(this)` to get the jquery element. No need to deal with the id directly. Indeed, you can use Rodolphe's `randomDiv` as the callback, just change his function to `$(this).css({`... – Supr Mar 22 '12 at 15:19
  • Updated fiddle based on the one you had with Rodolphe's code: http://jsfiddle.net/sM32J/2/ – Supr Mar 22 '12 at 15:23
  • cool! Didn't know you couldn't pass parameters to callback functions. is that an _always_ thing? or a jquery thing or a all programming languages thing? Is there *no* way to give the function a variable? At this point, what is the difference between "this" and "$(this)"? console.log(this) gives me the same as console.log($(this)). Thanks again for all your help! – 1252748 Mar 22 '12 at 15:42
  • It's an always thing in the sense that you can only pass a object, not a function call itself. `$('#div_' + tempId).fadeTo(delay[0], 0, giveRandomValue(tempId))` is actually calling `giveRandomValue(tempId)` immediately and passing along the *result*. What you could do if you wanted to is to create a function that returns a function with the parameters contained in a closure, but this is more advanced and a completely unnecessary (but fun!) complication. (Google closure to learn more.) – Supr Mar 22 '12 at 15:51
0

Give your div element to the randomDiv function and it should work :)

function randomColor() {
  return '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).toUpperCase();
}

function randomOpacity() {
  return Math.floor(Math.random() * 100) / 100;
}

function randomDiv(div) {
  $(div).css({
    'background-color': randomColor(),
    'opacity': randomOpacity()
  });
}
  • Thanks, both! I'm still having trouble with the callback part of this. That always seems to give me trouble. Rodolphe, I tried your solution here ( http://jsfiddle.net/loren_hibbard/sM32J/ ). Can you tell me what I did wrong. – 1252748 Mar 22 '12 at 14:57