Arno Lorentz Arno Lorentz - 3 months ago 9
CSS Question

Dynamic CSS with jQuery?

I've created a custom dropdown element.

The number of options it can have is based on a Database Table (I haven't created the Table yet). Like the number of options can be 4 or even 5 or anything for that matter.

I'll use PHP to give the number of options for the dropdown. Each of the options are in an

li
tag. The
li
siblings are inside the
ul
tag.

I have a CSS file which animates the
li
items. But instead of animating them all at once (in which case I would just animate the
ul
and would get the same effect), what I want to do is to animate them one by one:

Each
li
will have a delay which is progressive. For example if the first
li
has a
0s
delay and a duration of
300ms
then the second will start when the first ends, that is the second
li
will have a delay of
300ms
with the same duration. The duration remains the same, just the
delay
changes so as to give it a follow-the-previous kind of effect.

Since I don't know the number of options in the dropdown, how am I gonna do the same? I'm assuming it would require calculations but since CSS doesn't support it, there is no way to do it using native CSS.

My best guess is to use jQuery. Am I correct?

Answer

I'm not sure if you want jquery, but I know how to solve this problem using jQuery. This essentially adds a delay of 300ms per iteration over your options list that you fetch from the database after appending them to the parent list.

<script type='text/javascript'>
  $(document).ready(function(){
    var items = ['a', 'b', 'c', 'd', 'e']; //Whatever you fetch from the database
    for(var i =0; i<items.length; i++) {
     var new_item = $('<p>'+items[i]+'</p>').hide();
      $('#test').append(new_item); //Here test is the id of the unordered list.
      new_item.delay(i*300).fadeIn(300);
    }
  });
</script>

And you need to include this in your HTML -

<ul id="test">
</ul>

Don't forget to include jQuery!