Search code examples
jqueryloopstriggersclickcycle

jQuery trigger click on elements cycling


I have elements in page:

<a class="element" onclick="do this"></a>
<a class="element" onclick="do this"></a>
<a class="element" onclick="do this"></a>
<a class="element" onclick="do this"></a>

i need to trigger the click on each one and delay some time between the triggered clicks.

//for each one .element
$('.element').delay(800).trigger('click');

then i need to repeat this cycle as infite cycle, BUT i need to stop it when user click on a .element

i tryed many things like $.each( loop trigger); but i can't understand how to cycle all to infinite and stop it when i sad :(


Solution

  • There might exist more elegant solution, but here are my two cents:

    ​$(function(){
        $("a").on("click", function(e, d){
            $(this).addClass("active").siblings().removeClass("active");
            if(d !== true) {
                clearInterval(timer);
            }
        });
    
        $("a:first").addClass("active");
        var timer = setInterval(doClick, 800);
    
        function doClick() {
            var $n = $(".active").next();
            if ($n.length == 0) {
                $n = $(".active").siblings().first();
            }
            console.log($n.length);
            $n.trigger("click", [true]);
        }
    });
    ​
    

    jsFiddle