Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch divs every 10secs using jquery?

I have two div's setup that when clicked on a link switch from blue to orange. The sit in the same place and just give the impression of swapping from one colour to the other. This is my jquery:

jQuery(document).ready(function( $ ) {
    $(".dab").click(function(){
        $("#pf-orange-area").show();
        $("#pf-blue-area").hide();
    });
    $(".pfs").click(function(){
        $("#pf-orange-area").hide();
        $("#pf-blue-area").show();
    });
});

How I keep that functionality but also make them switch every 10 secs automatically?

like image 872
Rob Avatar asked Jan 12 '23 11:01

Rob


2 Answers

jQuery(function($) {

    var $or = $("#pf-orange-area"),
        $bl = $("#pf-blue-area"),
        changeColor;

    $(".dab").click(function(){
        $or.show();
        $bl.hide();
    });

    $(".pfs").click(function(){
        $or.hide();
        $bl.show();
    });

    changeColor = function() {
        $or.toggle();
        $bl.toggle();
    };

    setInterval(changeColor, 10000);
});

Thus, one of his colored elements must come now hidden and the other displayed.

like image 177
Maykonn Avatar answered Jan 21 '23 17:01

Maykonn


Use setInterval() in your code. Something like this

jQuery(document).ready(function ($) {
    var toggle = function () {
        $("#pf-orange-area, #pf-blue-area").toggle();
    }
    var anim = setInterval(toggle, 1000);
    $('button').on('click', function () {
        clearInterval(anim);
    });
});

To pause/stop animation then

clearInterval(anim);

Check this Updated JSFiddle

like image 20
Praveen Avatar answered Jan 21 '23 16:01

Praveen