Firstly, sorry for my bad english, I hope I'll explain well my problem...
So, I'm trying to learn developping and actually I have this code :
<ul>
<li class="odd ajax_block_product {if $smarty.foreach.myhomeFeaturedProducts.first}first_item{elseif $smarty.foreach.myhomeFeaturedProducts.last}last_item{else}item{/if} {if $smarty.foreach.myhomeFeaturedProducts.iteration%$nbItemsPerLine == 0}last_item_of_line{elseif $smarty.foreach.myhomeFeaturedProducts.iteration%$nbItemsPerLine == 1} {/if} {if $smarty.foreach.myhomeFeaturedProducts.iteration > ($smarty.foreach.myhomeFeaturedProducts.total - $totModulo)}last_line{/if}">...</li>
<li class="even ajax_block_category {if $smarty.foreach.myhomeFeaturedCategories.first}first_item{elseif $smarty.foreach.myhomeFeaturedCategories.last}last_item{else}item{/if}">...</li>
</ul>
The UL populates automaticly with smarty, so at the end my HTML is like this :
<ul>
<li class="odd">1</li>
<li class="odd">2</li>
<li class="odd">3</li>
<li class="odd">4</li>
<li class="even">5</li>
<li class="even">6</li>
<li class="even">7</li>
<li class="even">8</li>
</ul>
My problem is that I want to alternate EVEN and ODD classes with jQuery or PHP, but I didn't find how. I would like to make this :
<ul>
<li class="odd">1</li>
<li class="even">5</li>
<li class="odd">2</li>
<li class="even">6</li>
<li class="odd">3</li>
<li class="even">7</li>
<li class="odd">4</li>
<li class="even">8</li>
</ul>
Can somebody tell me how I need to do this please?
Thank you!
I find how to do this. Thank you all for helping me ! Here's the code for someone in my situation :
$(function () {
var $oddArray = new Array();
var $evenArray = new Array();
$('ul#shuffle li').each(function () {
if ($(this).hasClass('product')) {
$oddArray.push($(this).html());
} else {
$evenArray.push($(this).html());
}
});
var newLi = new Array();
var index;
var oddIndex = 0;
var evenIndex = 0;
for (index = 0; index < ($oddArray.length + $evenArray.length); index++) {
if (index % 2 == 0) {
console.log("ODD");
if ($oddArray[oddIndex] != undefined)
newLi += '<li>' + $oddArray[oddIndex] + '</li>';
oddIndex++;
} else {
console.log("EVEN");
if ($evenArray[evenIndex] != undefined)
newLi += '<li>' + $evenArray[evenIndex] + '</li>';
evenIndex++;
}
}
delete $oddArray;
delete $evenArray;
$('ul#shuffle').html(newLi);
});
Try using CSS :nth-child pseudo class like below,
li:nth-child(even) { color: green; }
li:nth-child(odd) { color: blue; }
Why don't just use smarty's cycle:
<li class="{cycle values="odd,even"} ajax_block_product....
Your code seems to be a bit complicated :
$(function () {
var $items = $('li');
var odd = $items.filter('.odd').get();
var even = $items.filter(':not(.odd)').get();
var mixed = [];
while (odd.length) {
mixed.push(odd.shift());
if (even.length) {
mixed.push(even.shift());
}
}
if (even.length) {
mixed = mixed.concat(even);
}
$('ul').append(mixed);
});
Here is a demo : http://jsfiddle.net/wared/unzxv/.