0

I've just take a look on a lot of answer on stack but nothing seems can work on this. I'me trying to apply a style to all element of a list li sequentially using delay. The script show just the last item of the list. What's the problem? thanks in advance for your help

$('ul li').each(function(i){
licont = this
  setTimeout(function(){
    $(licont).css('opacity','1')
  },i * 10);                  
});
li{
  opacity:0;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>ITEM 1</li>
  <li>ITEM 2</li>
  <li>ITEM 3</li>
  <li>ITEM 4</li>
</ul>
vlk
  • 1,414
  • 1
  • 13
  • 22

1 Answers1

3

You can pass the current element as a jQuery object as a parameter to setTimeout to reference current jQuery object within .each() when function passed to setTimeout is called

$('ul li').each(function(i) {
  setTimeout(function(el) {
    el.css('opacity', '1')
  }, i * 1000, $(this));
});
li {
  opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>ITEM 1</li>
  <li>ITEM 2</li>
  <li>ITEM 3</li>
  <li>ITEM 4</li>
</ul>
guest271314
  • 1
  • 15
  • 104
  • 177
  • Thank you, I was looking a better way to pass the current element to child functions for other applications also. – vlk May 11 '17 at 20:14
  • What do you mean by "better"? What are "child functions"? – guest271314 May 11 '17 at 20:17
  • See also [Execute function queue in javascript](http://stackoverflow.com/questions/32028368/execute-function-queue-in-javascript), [When the page is loaded,how to make six functions executed by each otherr?](http://stackoverflow.com/questions/43567064/when-the-page-is-loaded-how-to-make-six-functions-executed-by-each-otherr/) – guest271314 May 11 '17 at 20:22
  • I was using a var licont = this to pass the current element inside the setTimeout function. I think your is a better way to do it. I mean I was looking for this. – vlk May 11 '17 at 20:23