Loop function executed onclick JavaScript

Hi guys i’m trying to create a loop function so that each time the button is clicked the content will change. Where am I going wrong? right now it’s going to changeTestimonial2 when I click the button (the last in the loop)

function arrayOfTestimonials() {
    var arrayOfFunctions = [];
    arrayOfFunctions.push(changeTestimonial);
    arrayOfFunctions.push(changeTestimonial1);
    arrayOfFunctions.push(changeTestimonial2);

    for (var i = 0; i < arrayOfFunctions.length; ++i) {
        arrayOfFunctions[i](); // run your function
    }
}

3 thoughts on “Loop function executed onclick JavaScript”

  1. The way you wrote this code, it should work. I made the test…

    code

    <body>
        <script type="text/javascript">
            console.log("test");
    
            var fun1 = function(){
                console.log("fun1");
            }
    
            var fun2 = function(){
                console.log("fun2");
            }
    
            var fun3 = function(){
                console.log("fun3");
            }
    
            function arrayOfTestimonials() {
                var arrayOfFunctions = [];
                arrayOfFunctions.push(fun1);
                arrayOfFunctions.push(fun2);
                arrayOfFunctions.push(fun3);
    
                for (var i = 0; i < arrayOfFunctions.length; ++i) {
                    arrayOfFunctions[i](); // run your function
                }
            }
    
            arrayOfTestimonials();
        </script>
    </body>
    

    output

    test
    fun1
    fun2
    fun3
    
    Reply

Leave a Comment