javascript - Change the position of a list item when clicked -


on algorithm can solve following problem? need when click on 1 of menu block received class active , got in middle.

<ul>     <li>1</li>     <li>2</li>     <li>3</li>     <li class="active">4</li>     <li>5</li> </ul>  ul li {     float: left;     list-style: none;     background: red;     margin-left: 20px;     display: block;     padding: 20px; }  .active {     background: orange; } 

fiddle

for adding active class below

var lielems = document.getelementsbytagname('li'), mid = math.floor(lielems.length/2); array.prototype.foreach.call(lielems, function (item, idx) {     item.idx = idx;     item.onclick = function () {         document.queryselector('li.active').classlist.remove('active');         this.classlist.add('active');     }; }); 

demo: fiddle


var lielems = document.getelementsbytagname('li'),     length = lielems.length,     mid = math.floor(lielems.length / 2); array.prototype.foreach.call(lielems, function (item, idx) {     item.idx = idx;     item.onclick = function () {         document.queryselector('li.active').classlist.remove('active');         this.classlist.add('active');           if (lielems[mid].idx != mid) {             if (lielems[mid].idx == length - 1) {                 this.parentnode.appendchild(lielems[mid])             } else {                 this.parentnode.insertbefore(lielems[mid], lielems[lielems[mid].idx])             }         }          var pos = mid < this.idx ? mid : mid + 1;         this.parentnode.insertbefore(this, lielems[pos])      }; }); 

demo: fiddle


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -