I am trying to make navigation that will align the items no matter the quantity. In the else
I'm trying to give the li
before- and after the median-li
certain css. At the moment all li
are yellow because the index
number will always be larger than the median after it finished its loop. My js knowledge is not that great but I'm learning every day :)
var count = $("ul.filter__dropdown li").length;
if ( (count & 1) == 0 ) {
//even
var w = 100;
var list = $("ul.filter__dropdown li");
list.css('width', "calc( 100% /" + count + ")");
}
else {
//odd
var median = Math.round(count /= 2);
var list = $("ul.filter__dropdown li");
var count = $("ul.filter__dropdown li").length;
list.css('width', "calc( 100% /" + count + ")");
$("ul.filter__dropdown li").each(function(index) {
if ( index < median ) {
list.css("background-color" , "black");
}
if ( index == median ) {
list.css("background-color" , "green");
}
if ( index > median ) {
list.css("background-color" , "yellow");
}
})
}
You can use :lt
and :gt
selectors to select the li
elements before median and after
some index i.e. median respectively.
var total = $('li').length,
median = Math.floor(total / 2);
$('li:lt(' + median + ')').addClass('green');
$('li:gt(' + median + ')').addClass('red');
// $('li').eq(median).addClass('median');
li {
color: yellow;
}
.green {
color: green;
}
.red {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
</ul>