Gov
Gov

Reputation: 33

How to trigger two or three clicks in a javascript loop

I am trying to click a button or li on document ready, in this case twice or more, depending on the JavaScript loop.

The below code will alert from 1 to 2 but will only trigger once, any idea's how to trigger based on the loop i++

$(document).ready(function() {  
    for(var i = 0; i < 2; ){
        $("#inc"+this_item.food_menu_id+"").trigger("click");
        i++;
    }
});

The trigger will only execute the once.

I need to execute as per the number of i result. i.e 2 triggers not one.

Upvotes: 0

Views: 462

Answers (1)

JS_INF
JS_INF

Reputation: 467

  1. You need is to store the element in variable to make the loop executed normally
  2. Your loop isn't on the right way you should done it like that

HTML

<div id="elem">click</div>

Vanillajs

var elem = document.getElementById("elem"), n = 0;
elem.addEventListener("click", function () {
   n++;
   alert("trigger ("+n+")\n");
});
for(var i = 0; i < 5; i++) {
  elem.click();
}

jQuery

var n = 0, e = $("#elem");
e.click(function () {
    n++;
    alert("trigger ("+n+")\n");
});
for(var i = 0; i < 5; i++) {
  e.trigger("click");
}

Upvotes: 1

Related Questions