jQuery Rapid Class Switcher

http://jsfiddle.net/JamesKyle/re73T/

Trying to make a class switcher that will do the following:

  1. On Load - randomly select one of 10 classes to add to an element
  2. While Hovering - Rapidly (every 0.4s) switch between 10 classes
  3. On mouseOut - leave the current class active

I've tried several ways of doing this, none of which have worked.

What do you think would be the best way to do this?

Answers


Here's a different implementation that works in your jsFiddle here: http://jsfiddle.net/jfriend00/b7A4a/. This one also makes sure that the randomly generated class name is different than the previous one so the color actually changes every 400ms rather than skipping a change 1 out of 10 times because it generates the same color value that it just had.

// get unique random class that's different than what is currently being used
function getRandomClass(prior) {
    var r;
    do {
        r = "class" + (Math.floor(Math.random() * 10) + 1); 
    } while (prior && prior.match(new RegExp("\\b" + r + "\\b")));
    return(r);
}

// initialize the current class
$(".element").addClass(getRandomClass());

// upon hover, start the timer, when leaving stop the timer
$(".element").hover(function() {
    var self = this;
    if (this.intervalTimer) {
        clearInterval(this.intervalTimer);
        this.intervalTimer = null;
    }
    this.intervalTimer = setInterval(function() {
        var c = self.className;
        self.className = c.replace(/\bclass\d+\b/, getRandomClass(c));
    }, 400);
}, function() {
    clearInterval(this.intervalTimer);
    this.intervalTimer = null;
});

http://jsfiddle.net/re73T/9/

// On Load
//     Randomly select 1 of 10 classes


function removeAllClasses() {
    var i;
    for (i = 0; i <= 10; i += 1) {
        $('.element').removeClass('class' + i);
    }
}

function setRandomClass() {
    var cls = "class"+Math.floor(Math.random() * (10 - 1 + 1) + 1);
    $('.element').addClass(cls);
}

$(document).ready(function() {
    removeAllClasses(); // just in case
    setRandomClass();
});

// While Hovering
//    every 0.4s 
//        switch to the next class out of ten
// I want it to leave the current class when you mouseout
var IS_HOVERING = false;
$('.element').hover(function() {
    IS_HOVERING = true;
}, function() {
    IS_HOVERING = false;
});

function onTimeout() {
    if (IS_HOVERING) {
        removeAllClasses();
        setRandomClass();
    }
    setTimeout(onTimeout, 400);
}

setTimeout(onTimeout, 400);

Need Your Help

PerformanceCounterType for average time

c# visual-studio-2010 unit-testing performancecounter

I have created some Load Tests to an HTTP server which consist of simple Unit Tests. Each unit test sends an http request to the server. Now I want to keep some extra information about each load te...

Use one action listener for all buttons

java

I have for example 10 buttons in my frame.