Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery + Css - Adding css dynamically to list items

Tags:

jquery

css

I am wondering if there is a way to select list items an incrimentally add a css value as the list goes on.

It is hard to explain so let me show and example:

<ul class="list">
<li></li>
<li></li>
<li></li>
<li></li>
....
</ul>

I would like to take a dynamically generated list like this and

<ul class="list">
    <li style="left:0px;"></li>
    <li style="left:10px;"></li>
    <li style="left:20px;"></li>
    <li style="left:30px;"></li>
    ....
</ul>

I'm not sure if this is best done with jQuery, or if there is a type of CSS selector I don't know about that could pull this off.

If I were to use jQuery, i think it might go something like this:

$('.list > li:nth-child(2)').css('left', '+=10px').next

But I am not sure how to scrub through the rest of the list and keep adding 10px every time. I've been playing the the idea of using '.next' and '.prev' but am unsure how to execute.

Thanks in advance for your patience, I'm a novice at jQuery.

like image 412
patrick Avatar asked May 05 '12 17:05

patrick


People also ask

How to add dynamic CSS in jQuery?

To add CSS properties dynamically, we use css() method. The css() method is used to change style property of the selected element. Here we have created two elements inside body tag i.e. <h1> and <h3> elements. We apply CSS property on <body> tag and <h1> tag using css() method dynamically.

How to add CSS attribute using jQuery?

Syntax: $(). css(propertyname, value); $(). css(properties);

Can we change CSS dynamically?

color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element. For example, you could set the colour of an element to red by calling element.

How do you add dynamics to elements in CSS?

To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript. Approach: The className property used to add a class in JavaScript.


1 Answers

You can use each and the index parameter as a control. I used margin-left here for my example, but obviously just left will work in your case also.

http://jsfiddle.net/nEePk/

$('li').each( function(index) {
    $(this).css('margin-left', index * 10);
});​

As far as a CSS only means, I don't think this will be possible. The reason is that there is no math that can be done in the actual expression. You can certainly select each li using the immediate sibling selector though.

li ~ li { ... } 
like image 126
mrtsherman Avatar answered Sep 19 '22 23:09

mrtsherman