Engkus Kusnadi Engkus Kusnadi - 3 days ago 5
Javascript Question

Automatic click an element one by one at same class name

When I run the fiddle, the text "a" should be changed automatic without

click
event, and it must changed one by one with a delay, How do I do that?



$(document).ready(function() {
var element = ".pictures";
var delay = 2 * 1000; //2 Seconds

function change() {
$(element).one('click', function() {
$(this).text("Changed");
})
}

change();
setInterval(change(), delay);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pictures">a</div>
<div class="pictures">a</div>
<div class="pictures">a</div>
<div class="pictures">a</div>
<div class="pictures">a</div>
<div class="pictures">a</div>





Here's the fiddle

Answer

You need to trigger() the click handler in the change function. Additionally you need to pass the function reference to setInterval() method, also use clearInterval() to cancel the action once all elements are clicked.

$(document).ready(function() {

  //Cache elements
  var element = $(".pictures");

  //variable to maintain index of clicked item
  var i = 0;

  //2 Seconds
  var delay = 2 * 1000;

  //Bind event handler
  element.one('click', function() {
    $(this).text("Changed");
  })

  function change() {
    if (i == element.length && interval) {
      clearInterval(interval);
    }

    //get element at index using .eq() and trigger click handler
    element.eq(i++).trigger('click');
  }

  //Execute on page load
  change();

  //On interval
  var interval = setInterval(change, delay);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pictures">a</div>
<div class="pictures">a</div>
<div class="pictures">a</div>
<div class="pictures">a</div>
<div class="pictures">a</div>
<div class="pictures">a</div>

Update Fiddle

Comments