3

I have a question. How to gradually change the class, every 60 seconds. And is it possible to connect to the Functions of the current time?

This is an example but it will not change the class every 60 seconds

Here is my code:

$(function() {
    function test() {
        $('#test1').switchClass('class1', 'class2', 1000);

        if($('#test1').hasClass('class1'))
        {
            $('#test1').switchClass('class2', 'class1', 1000);
        }
        else
        {
            $('#test1').switchClass('class1', 'class2', 1000);
        }
    }

    // run function
    test();

    // loop function
    setInterval(function() { test();}, 1000);

});

css code:

.class1 {
    width: 400px;
    height: 200px;
    background: lightgray;
    transition: all 60s ease-out;
    -webkit-transition: all 60s ease;
    -moz-transition: all 60s ease;
    -o-transition: all 60s ease;
}

.class2 {
    width: 400px;
    height: 200px;
    background: orange;
    transition: all 60s ease-out;
    -webkit-transition: all 60s ease;
    -moz-transition: all 60s ease;
    -o-transition: all 60s ease;
}
G.V.
  • 37
  • 1
  • 1
  • 6

2 Answers2

5

I'm not entirely sure if this is what you are asking, but toggleClass enables classes that are disabled, and vice-versa:

$(function() {
    function test() {
        $('#test1').toggleClass('class1 class2');
    }

    test();

    // loop function
    setInterval(test, 60000);
});

Of course, your transition speed has to match your setInterval interval time. Your transition currently takes one minute, but you are changing class every second.

Faster demo: http://jsfiddle.net/7UsHV/

Jeff B
  • 29,943
  • 7
  • 61
  • 90
3

The durations on the setInterval and animations need to match. I changed them to 2 seconds to make it easier to see:

http://jsfiddle.net/r6JV6/

setInterval(function() { 
    $('#test1').toggleClass('class1 class2'); 
}, 2000);

If you're really only doing the background color, it might be simpler to do a recursive jQuery animation. Here's a version that uses switchClass() and doesn't use css transitions:

http://jsfiddle.net/B3xac/

function switchTheClass() {
    var removeClass, addClass;
    if ($('#test1').hasClass('class1')) {
        removeClass = 'class1';
        addClass = 'class2';
    } else {
        removeClass = 'class2';
        addClass = 'class1';
    }
    $('#test1').switchClass(removeClass, addClass, 2000, function () {
        switchTheClass();
    });
}

$(function () {

    switchTheClass();

});
Jason P
  • 26,984
  • 3
  • 31
  • 45