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>

1
  • I think you left out the variable declaration in line 2, can you edit? Commented May 11, 2017 at 20:05

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you, I was looking a better way to pass the current element to child functions for other applications also.
What do you mean by "better"? What are "child functions"?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.