How can show specific number of li using jquery? - javascript

I want to show 3 li and after 1 second these 3 li will be slide up and next 3 li will be automatically show up in the div.#content
<div id="content">
<ul>
<li>122</li>
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
<li>fifth</li>
<li>sixth</li>
</ul>
</div>
I tried toggle with setTimeout function, but it does fulfill on my requirements. I know this question may be stupid for someone but believe I really need your guideline please guide me how can i done this task. I will appreciate if someone guide me. I don't want to use any plugin.

A better way (not a semantic way, but) to achieve this is to wrap every 3 <li> and then walk through them. One way is:
$(function () {
var lis = $("ul > li");
for(var i = 0; i < lis.length; i+=3) {
lis.slice(i, i+3).wrapAll("<div class='slide'></div>");
}
$(".slide").hide();
$(".slide:first").slideDown();
setInterval(function () {
if ($(".slide:visible").next(".slide").length == 0) {
$(".slide:visible").slideUp(function () {
$(".slide:first").slideDown();
});
}
else
$(".slide:visible").slideUp(function () {
$(this).next(".slide").slideDown();
});
}, 2500);
});
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<div id="content">
<ul>
<li>122</li>
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
<li>fifth</li>
<li>sixth</li>
</ul>
</div>

You can use :lt() and :gt() pseudo selectors
var i = 2,
$ul = $('#content ul'),
int = setInterval(function() {
$('li', $ul).slideUp();
$('li:gt(' + i + '):lt(3)', $ul).slideDown();
i += 3;
if (i + 1 >= $('li', $ul).length) clearInterval(int);
},
2000)
#content ul li:nth-child(n+4) {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
<ul>
<li>122</li>
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
<li>fifth</li>
<li>sixth</li>
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
<li>fifth</li>
<li>sixth</li>
</ul>
</div>
UPDATE:
If you want to slide continuously then following code can be used
var i = 2,
$ul = $('#content ul'),
int = setInterval(function() {
$('li', $ul).slideUp();
$('li' + (i == -1 ? '' : ':gt(' + i + ')') + ':lt(3)', $ul).slideDown();
i += 3;
if (i + 1 >= $('li', $ul).length) i = -1;
},
2000)
#content ul li:nth-child(n+4) {
display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
<ul>
<li>122</li>
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
<li>fifth</li>
<li>sixth</li>
<li>first</li>
<li>second</li>
<li>third</li>
<li>fourth</li>
<li>fifth</li>
<li>sixth</li>
</ul>
</div>

You can try this:
$("li").hide(); // this will hide all li first
$('ul li:lt(3)').show(); // this will display first 3 li from all li

You can do like this,
$("#content ul li").hide();
i = 0;
setInterval(function() {
i = (i + 3) % $("#content ul li").length;
$("#content > ul >li").slideUp();
$("#content > ul >li:gt(" + i + ")").slideDown();
$("#content > ul >li:gt(" + (i + 3) % $("#content ul li").length + ")").hide();
}, 1000);
Fiddle

Here is another possibility:
var steps = 3;
$(function tick() {
setTimeout(function () {
var top = '-=' + (steps * 31) + 'px';
var lis = $('li:lt(' + steps + ')');
var clones = lis.clone().appendTo('ul');
$.when(
$('li').animate({ top: top }, 'slow')
).done(function () {
clones.remove();
lis.appendTo('ul');
$('li').css('top', 'auto');
tick();
});
}, 1000);
});
* {
padding: 0;
margin: 0;
}
ul {
overflow: hidden;
height: 92px;
}
li {
display: block;
position: relative;
line-height: 30px;
padding: 0 10px;
background: #DDD;
margin-bottom: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul><li>A</li><li>B</li><li>C</li><li>D</li><li>E</li><li>F</li><li>G</li><li>H</li></ul>

Related

Adding Multiple Vanilla JavaScript Tabs to the Same Page

Using a variation of the following code, I was able to successfully add one set of Vanilla JavaScript tabs.
Yet how to do I add multiple sets of JavaScript tabs to one page using the same classes in the HTML.
I'm having difficultly creating unique dynamic IDs for the tab selectors and tab content areas using JavaScript. As you can see in https://www.w3.org/TR/wai-aria-practices/examples/tabs/tabs-1/tabs.html, these unique IDs are needed for accessible tags.
var accessibleTabsContainers = document.querySelectorAll('.accessible-tabs-container');
var tabSelector = document.querySelectorAll('.tab-selectors > li');
var tabContent = document.querySelectorAll('.tab-contents > div');
var largeRandNumber = Math.floor((Math.random() * 1000) + 1000);
accessibleTabsContainers.forEach(function(elem, indexAccessibleTabContainer) {
elem.setAttribute('data-id', indexAccessibleTabContainer);
tabSelector.forEach(function(singleTabSelector, i) {
var ariaControlTabContent = 'tab-content-' + largeRandNumber + '-' + i + '_' + indexAccessibleTabContainer;
var tabSelectorId = 'tab-selector-' + largeRandNumber + '-' + i + '_' + indexAccessibleTabContainer;
singleTabSelector.setAttribute('data-id', i);
singleTabSelector.setAttribute('id', tabSelectorId);
singleTabSelector.setAttribute('aria-controls', ariaControlTabContent);
tabContent[i].setAttribute('data-id', i);
tabContent[i].setAttribute('tabindex', 0);
tabContent[i].setAttribute('role', 'tabpanel');
tabContent[i].setAttribute('id', ariaControlTabContent);
tabContent[i].setAttribute('aria-labeledby', tabSelectorId);
if(i === 0) {
tabSelector[i].setAttribute('aria-pressed', 'true');
} else {
tabSelector[i].setAttribute('aria-pressed', 'false');
tabSelector[i].setAttribute('tabindex', -1);
}
});
});
function onTabSelectorClick(e) {
accessibleTabsContainers.forEach(function(accessibleTabsContainer, indexAccessibleTabContainer) {
var tabSelectorSelected = e.target;
var accessibleTabsContainerSelected = tabSelectorSelected.parentElement.parentElement;
if(!tabSelectorSelected.classList.contains('active-tab-selector')) {
var tabSelectorSelectedFromContainer = accessibleTabsContainerSelected.querySelectorAll('.tab-contents > div');
console.log(tabSelectorSelectedFromContainer);
tabSelector.forEach(function(singleTabSelected, i) {
if(tabSelectorSelected.getAttribute('data-id') === tabContent[i].getAttribute('data-id')) {
tabContent[i].classList.add('tab-content-active');
} else {
tabSelector[i].classList.remove('active-tab-selector');
tabSelector[i].setAttribute('aria-pressed', 'false');
tabSelector[i].setAttribute('aria-selected', 'false');
tabSelector[i].setAttribute('tabindex', -1);
tabContent[i].classList.remove('tab-content-active');
}
});
tabSelectorSelected.classList.add('active-tab-selector');
tabSelectorSelected.setAttribute('aria-pressed', 'true');
tabSelectorSelected.setAttribute('aria-selected', 'true');
tabSelectorSelected.removeAttribute('tabindex');
}
});
}
tabSelector.forEach(function(tabSelector) {
tabSelector.addEventListener('click', onTabSelectorClick);
});
.wrapper {
max-width: 960px;
margin: 0 auto;
}
.tab-selectors {
display: inline-block;
}
.tab-selectors > li {
padding: 10px;
}
.tab-selectors > .active-tab-selector {
border: 1px solid #f00;
}
.tab-content {
display: inline-block;
}
.tab-contents > div {
padding: 10px;
border: 2px solid #000;
height: 150px;
width: 150px;
display: none;
}
.tab-contents > .tab-content-active {
display: block;
}
<div class="wrapper">
<h1>Accessible Tabs using Vanilla JavaScript</h1>
<div class="accessible-tabs-container">
<ul role="tablist" aria-lable="Tabs Example" class="tab-selectors">
<li class="active-tab-selector">Tab Selector 1</li>
<li>Tab Selector 2</li>
<li>Tab Selector 3</li>
</ul>
<div class="tab-contents">
<div class="tab-content-active">
Tab Content 1
</div>
<div>
Tab Content 2
</div>
<div>
Tab Content 3
</div>
</div>
</div>
<div class="accessible-tabs-container">
<ul role="tablist" aria-lable="Tabs Example" class="tab-selectors">
<li class="active-tab-selector">Tab Selector 1</li>
<li>Tab Selector 2</li>
<li>Tab Selector 3</li>
</ul>
<div class="tab-contents">
<div class="tab-content-active">
Tab Content 1
</div>
<div>
Tab Content 2
</div>
<div>
Tab Content 3
</div>
</div>
</div>
</div>
I'm trying to generate these unique IDs in line 6 of the Vanilla JavaScript (accessibleTabsContainers.forEach) but it's not working.
Any assistance would be appreciated.
I solved my own issue. In the forEach loop that iterates inside the onTabSelectorClick function, I refactored the code to add the lines below:
var tabSelectorSelected = e.target;
var accessibleTabsContainerSelected = tabSelectorSelected.closest('.accessible-tabs-container');
var tabSelectorsSelectedFromTabs = accessibleTabsContainerSelected.querySelectorAll('ul > li');
Then in a forEach loop instead of iterating through tabSelector (which references var tabSelector = document.querySelectorAll('.tab-selectors > li');) and loops through all tabs li tags, not just the ones referenced by the element clicked, I used tabSelectorsSelectedFromTabs, which references the tab elements inside their parent div tag (var accessibleTabsContainerSelected = tabSelectorSelected.closest('.accessible-tabs-container');), from the tab element (li tag) clicked (var tabSelectorSelected = e.target;).
See https://codepen.io/hollyw00d/pen/JjYJWjG. Also, I added the correct code in this answer. Below is a more useful before and after description of the code:
Incorrect forEach Loop Snippet inside onTabSelectorClick function that is passed in Click Event Handler
var tabSelector = document.querySelectorAll('.tab-selectors > li');
function onTabSelectorClick(e) {
tabSelector.forEach(function() {
// Code here
});
}
Correct forEach Loop Snippet inside onTabSelectorClick function that is passed in Click Event Handler
var tabSelectorSelected = e.target;
var accessibleTabsContainerSelected = tabSelectorSelected.closest('.accessible-tabs-container');
var tabSelectorsSelectedFromTabs = accessibleTabsContainerSelected.querySelectorAll('ul > li');
function onTabSelectorClick(e) {
tabSelectorsSelectedFromTabs.forEach(function() {
// Code here
});
}
var accessibleTabsContainers = document.querySelectorAll('.accessible-tabs-container');
var tabSelector = document.querySelectorAll('.tab-selectors > li');
var tabContent = document.querySelectorAll('.tab-contents > div');
var largeRandNumber = Math.floor((Math.random() * 1000) + 1000);
accessibleTabsContainers.forEach(function(elem, indexAccessibleTabContainer) {
elem.setAttribute('data-id', indexAccessibleTabContainer);
tabSelector.forEach(function(singleTabSelector, i) {
var tabSelectorId = 'tab-selector-' + largeRandNumber + '_' + i + '_' + indexAccessibleTabContainer;
var ariaControlTabContent = 'tab-content-' + largeRandNumber + '_' + i + '_' + indexAccessibleTabContainer;
singleTabSelector.setAttribute('data-id', i);
singleTabSelector.setAttribute('id', tabSelectorId);
singleTabSelector.setAttribute('aria-controls', ariaControlTabContent);
tabContent[i].setAttribute('data-id', i);
tabContent[i].setAttribute('tabindex', 0);
tabContent[i].setAttribute('role', 'tabpanel');
tabContent[i].setAttribute('id', ariaControlTabContent);
tabContent[i].setAttribute('aria-labeledby', tabSelectorId);
if(i === 0) {
singleTabSelector.setAttribute('aria-pressed', 'true');
} else {
singleTabSelector.setAttribute('aria-pressed', 'false');
singleTabSelector.setAttribute('tabindex', -1);
}
});
});
function onTabSelectorClick(e) {
var tabSelectorSelected = e.target;
var accessibleTabsContainerSelected = tabSelectorSelected.closest('.accessible-tabs-container');
var tabSelectorsSelectedFromTabs = accessibleTabsContainerSelected.querySelectorAll('ul > li');
var tabContentsSelectedFromContainer = accessibleTabsContainerSelected.querySelectorAll('.tab-contents > div');
if(!tabSelectorSelected.classList.contains('active-tab-selector')) {
tabSelectorsSelectedFromTabs.forEach(function(singleTabSelected, i) {
if(tabSelectorSelected.getAttribute('data-id') === tabContentsSelectedFromContainer[i].getAttribute('data-id')) {
singleTabSelected.classList.add('active-tab-selector');
singleTabSelected.setAttribute('tabindex', 0);
singleTabSelected.setAttribute('aria-pressed', 'true');
tabContentsSelectedFromContainer[i].classList.add('tab-content-active');
} else {
singleTabSelected.classList.remove('active-tab-selector');
singleTabSelected.setAttribute('tabindex', -1);
singleTabSelected.setAttribute('aria-pressed', 'false');
tabContentsSelectedFromContainer[i].classList.remove('tab-content-active');
}
});
}
}
tabSelector.forEach(function(tabSelector) {
tabSelector.addEventListener('click', onTabSelectorClick);
});
.wrapper {
max-width: 960px;
margin: 0 auto;
}
.tab-selectors {
display: inline-block;
}
.tab-selectors > li {
padding: 10px;
}
.tab-selectors > .active-tab-selector {
border: 1px solid #f00;
}
.tab-content {
display: inline-block;
}
.tab-contents > div {
padding: 10px;
border: 2px solid #000;
height: 150px;
width: 150px;
display: none;
}
.tab-contents > .tab-content-active {
display: block;
}
<div class="wrapper">
<h1>Accessible Tabs using Vanilla JavaScript</h1>
<div class="accessible-tabs-container">
<ul role="tablist" aria-lable="Tabs Example" class="tab-selectors">
<li class="active-tab-selector">Tab Selector 1</li>
<li>Tab Selector 2</li>
<li>Tab Selector 3</li>
</ul>
<div class="tab-contents">
<div class="tab-content-active">
Tab Content 1
</div>
<div>
Tab Content 2
</div>
<div>
Tab Content 3
</div>
</div>
</div>
<div class="accessible-tabs-container">
<ul role="tablist" aria-lable="Tabs Example" class="tab-selectors">
<li class="active-tab-selector">Tab Selector 1</li>
<li>Tab Selector 2</li>
<li>Tab Selector 3</li>
</ul>
<div class="tab-contents">
<div class="tab-content-active">
Tab Content 1
</div>
<div>
Tab Content 2
</div>
<div>
Tab Content 3
</div>
</div>
</div>
</div>

Adding directional controls (prev/next) to switch between tabs

I've just finished a creating a bare bones JavaScript tabs functionality for website. Right now I'm having a bit of problem trying to add directional functions in order to switch between tabs. Here is what I've created so far. I'm not sue on how I can increment or decrement the index in order to use the directional arrows to switch tabs and also the content
$(document).ready(function() {
$('.tabs-list li:first-child').addClass('active'),
$('.tab-content .show-content:first-child').addClass('active');
$('.tabs-list li').click(function(e) {
event.preventDefault();
if (!$(this).hasClass('active')) {
var tabIndex = $(this).index();
var nthChild = tabIndex + 1;
// select the right elements
var $tabsList = $(this).parent();
var $tabContent = $tabsList.next('.tab-content');
$tabsList.find('li.active').removeClass('active');
$(this).addClass('active');
$tabContent.find('.show-content').removeClass('active');
$tabContent.find('.show-content:nth-child(' + nthChild + ')').addClass('active');
}
})
$('.prev').on('click', function() {});
$('next').on('click', function() {});
})
.tabs-list li {
display: inline-block;
}
.tab-content .show-content {
display: none
}
.tab-content .show-content.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul class="tabs-list">
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
</ul>
<div class="tab-content">
<div class="show-content">
Content 1
</div>
<div class="show-content">
Content 2
</div>
<di>
Content 3
</di>
</div>
</div>
<ul>
<li class="prev">Prev</li>
<li class="next">Next</li>
</ul>
You can do it using jQuery .prev() and .next() methods. You just need to get the current .active tab and change it accordingly.
Here's the code you need:
$('.prev').on('click', function() {
var current = $('.tab-content .show-content.active');
if (current.prev('.tab-content .show-content')[0]) {
current.removeClass('active');
current.prev('.tab-content .show-content').addClass('active');
}
});
$('.next').on('click', function() {
var current = $('.tab-content .show-content.active');
if (current.next('.tab-content .show-content')[0]) {
current.removeClass('active');
current.next('.tab-content .show-content').addClass('active');
}
});
Demo:
This is a working Fiddle and a working Demo snippet:
$(document).ready(function() {
$('.tabs-list li:first-child').addClass('active'),
$('.tab-content .show-content:first-child').addClass('active');
$('.tabs-list li').click(function(e) {
event.preventDefault();
if (!$(this).hasClass('active')) {
var tabIndex = $(this).index();
var nthChild = tabIndex + 1;
// select the right elements
var $tabsList = $(this).parent();
var $tabContent = $tabsList.next('.tab-content');
$tabsList.find('li.active').removeClass('active');
$(this).addClass('active');
$tabContent.find('.show-content').removeClass('active');
$tabContent.find('.show-content:nth-child(' + nthChild + ')').addClass('active');
}
})
$('.prev').on('click', function() {
var current = $('.tab-content .show-content.active');
if (current.prev('.tab-content .show-content')[0]) {
current.removeClass('active');
current.prev('.tab-content .show-content').addClass('active');
}
});
$('.next').on('click', function() {
var current = $('.tab-content .show-content.active');
if (current.next('.tab-content .show-content')[0]) {
current.removeClass('active');
current.next('.tab-content .show-content').addClass('active');
}
});
})
.tabs-list li {
display: inline-block;
cursor: pointer;
}
.tab-content .show-content {
display: none
}
.tab-content .show-content.active {
display: block;
}
.as-console-row-code {
display: none;
}
.prev,
.next {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul class="tabs-list">
<li>Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
</ul>
<div class="tab-content">
<div class="show-content">
Content 1
</div>
<div class="show-content">
Content 2
</div>
<div class="show-content">
Content 3
</div>
</div>
</div>
<ul>
<li class="prev">Prev</li>
<li class="next">Next</li>
</ul>
Edit:
To make it loop in a cyclic way and doesn't stop in first or last elements, we should just implement that in the else block of our if statement, so it won't stop.
Here's how will be your code:
$('.prev').on('click', function() {
var current = $('.tab-content .show-content.active');
if (current.prev('.tab-content .show-content')[0]) {
current.removeClass('active');
current.prev('.tab-content .show-content').addClass('active');
} else {
current.removeClass('active');
$(".tab-content .show-content:last").addClass('active');
}
});
$('.next').on('click', function() {
var current = $('.tab-content .show-content.active');
if (current.next('.tab-content .show-content')[0]) {
current.removeClass('active');
current.next('.tab-content .show-content').addClass('active');
} else {
current.removeClass('active');
$(".tab-content .show-content:first").addClass('active');
}
});
And this is an updated Fiddle taking in consideration these changes.

i want to store toggle state in cookie and also want to close previous list when next list is clicked

http://jsfiddle.net/deepansh/BHCZ4/2/ this is a fiddle.
I want to save toggle state in cookie so that after page reload I get the same state, and I want to close previously-open list after clicking for opening new list.
I want to do in in minimum lines.
HTML
<ul class="nav sidebar-nav" id="am_menu">
<li> <span>User</span>
<ul>
<li>Add User
</li>
<li>List User
</li>
<li>User Profile
</li>
</ul>
</li>
<li> <span>User</span>
<ul>
<li>Add User
</li>
<li>List User
</li>
<li>User Profile
</li>
</ul>
</li>
</ul>
CSS:
ul {
width: 200px;
}
img {
width: 14px;
}
li ul {
display: none;
}
li ul {
padding-left: 4em;
list-style:none;
}
li ul li {
line-height:35px;
}
li ul li ul {
padding-left: .5em;
}
JS
$(function () {
$('li').filter(function (i) {
return $('ul', this).length >= 1;
}).each(function (i) {
$(this).children("a")
.click(function (e) {
var $ul = $(this).next("ul");
if ($ul.is(":visible")) {
$ul.find("ul").toggle("slow()");
$ul.toggle("slow()");
} else {
$ul.toggle("slow()");
};
})
});
});
I'd personally take the approach (using, as in Arun's answer, the $.cookie plugin):
$(function () {
var toShow = $.cookie('lastShownIndex'),
topLevel = $('#am_menu').find('> li');
topLevel.click(function(){
$(this).children('ul').slideToggle().end().siblings().children('ul').slideUp();
$.cookie('lastShownIndex', $(this).index());
}).eq(toShow).find('ul').show();
});
JS Fiddle demo.
References:
children().
click().
end().
eq().
find().
index().
show().
slideUp().
jQuery cookie plugin is used
$(function () {
$('#am_menu li:has(ul) > a').click(function (e) {
var $ul = $(this).next("ul");
$ul.toggle("slow");
$('#am_menu li ul').not($ul).slideUp();
$.cookie('curr.menu', $(this).parent().index())
});
var cindex = $.cookie('curr.menu');
if (cindex != undefined) {
$('#am_menu li:has(ul)').eq(cindex).children('a').click()
}
});
Demo: Fiddle

How to sort a list with two items

Hello I want to make this two items sortable without using plugins and stuff, only HTML5 and pure javascript:
<ul ondragenter="return dragEnter(event)" ondrop="return dragDrop(event)"
ondragover="return dragOver(event)">
<li draggable="true" ondragstart="return dragStart(event)">Item 1</li>
<li draggable="true" ondragstart="return dragStart(event)">Item 2</li>
</ul>
well i've tried:
function dragStart(ev) {
ev.dataTransfer.effectAllowed = 'move';
ev.dataTransfer.setData("Text", ev.target.getAttribute('class'));
return true;
}
function dragEnter(ev) {
event.preventDefault();
return true;
}
function dragOver(ev) {
return false;
}
function dragDrop(ev) {
var src = ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(src));
ev.stopPropagation();
return false;
}
Would you like to order alphabetically? Here is a solution without any library.
var items = document.getElementsByTagName("li");
var values = [];
for(var i = 0; i < items.length; i++) {
values.push(items[i].innerHTML);
}
values.sort();
for(var i = 0; i < items.length; i++) {
items[i].innerHTML = values[i];
}
http://jsfiddle.net/GG9gG/
jsfiddle:
http://jsfiddle.net/pMcmL/6/
HTML:
<ul id="sortable">
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 1
</li>
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 2
</li>
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 3
</li>
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 4
</li>
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 5
</li>
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 6
</li>
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 7
</li>
</ul>
CSS:
http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/base/jquery-ui.css
+
li {
margin: 1px;
width: 130px;
padding:2px;
vertical-align:middle;
}
li span {
color: gray;
font-size: 1.1em;
margin-right: 5px;
margin-left: 5px;
cursor: pointer;
height:100%;
}
input[type="text"] {
width: 32px;
margin-right: 5px;
border: 1px solid lightgay;
color: blue;
text-align: center;
}
Javascript:
sort_ul = $('#sortable'); // * sortable <ul>
itemsCount = $('#sortable li').length; // * total number of items
function updateIndexes() { // * function to update
$('#sortable li input').each( // items numbering
function(i) {
$(this).val(i + 1);
});
}
updateIndexes(); // * start by update items numbering
sort_ul.sortable({handle: 'span', // * apply 'sortable' to <ul>
stop: function(event, ui){
updateIndexes(); // * when sorting is completed,
} // update items numbering
});
$('#sortable li input').keyup( // * watch for keyup on inputs
function(event) {
if (event.keyCode == '13') { // * react only to ENTER press
event.preventDefault(); // * stop the event here
position = parseInt($(this).val());// * get user 'new position'
li = $(this).parent(); // * store current <li> to move
if (position >= 1 // * proceed only if
&& position <= itemsCount){ // 1<=position<=number of items
li.effect('drop', function(){ // * hide <li> with 'drop' effect
li.detach(); // * detach <li> from DOM
if (position == itemsCount)
sort_ul.append(li); // * if pos=last: append
else // else: insert before position-1
li.insertBefore($('#sortable li:eq('+(position - 1)+')'));
updateIndexes(); // * update items numbering
li.effect('slide'); // * apply 'slide' effect when in
}); // new position
}else{ li.effect('highlight'); } // * if invalid position: highlight
}}});
Reference Link

Sortable list + ability to re-order each item by inputting rank #

I've searched and searched about how to do this, but to no avail.
Basically I have a pretty standard jQuery sortable list, using a gripper to allow users to rearrange the list
What I would like to add is an input box to each list item, autofilled with that item's #, that allows users to enter any number (so long as it is <== the total # of items in the list)< and then hit "Enter" or press a button to re-order the list.
Please see the YouTube Playlist tool or Netflix Queue as an example of what I am referring to:
http://img195.imageshack.us/img195/7715/youtubeplaylistrearrangc.png
http://www.thedigeratilife.com/images/netflix-queue-big.jpg
I cannot figure this out - Any assistance would be greatly appreciated!
Dave
jsfiddle:
http://jsfiddle.net/pMcmL/6/
HTML:
<ul id="sortable">
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 1
</li>
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 2
</li>
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 3
</li>
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 4
</li>
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 5
</li>
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 6
</li>
<li class="ui-state-default">
<span>⇅</span><input type="text"/>Item 7
</li>
</ul>
CSS:
http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/base/jquery-ui.css
+
li {
margin: 1px;
width: 130px;
padding:2px;
vertical-align:middle;
}
li span {
color: gray;
font-size: 1.1em;
margin-right: 5px;
margin-left: 5px;
cursor: pointer;
height:100%;
}
input[type="text"] {
width: 32px;
margin-right: 5px;
border: 1px solid lightgay;
color: blue;
text-align: center;
}
Javascript:
sort_ul = $('#sortable'); // * sortable <ul>
itemsCount = $('#sortable li').length; // * total number of items
function updateIndexes() { // * function to update
$('#sortable li input').each( // items numbering
function(i) {
$(this).val(i + 1);
});
}
updateIndexes(); // * start by update items numbering
sort_ul.sortable({handle: 'span', // * apply 'sortable' to <ul>
stop: function(event, ui){
updateIndexes(); // * when sorting is completed,
} // update items numbering
});
$('#sortable li input').keyup( // * watch for keyup on inputs
function(event) {
if (event.keyCode == '13') { // * react only to ENTER press
event.preventDefault(); // * stop the event here
position = parseInt($(this).val());// * get user 'new position'
li = $(this).parent(); // * store current <li> to move
if (position >= 1 // * proceed only if
&& position <= itemsCount){ // 1<=position<=number of items
li.effect('drop', function(){ // * hide <li> with 'drop' effect
li.detach(); // * detach <li> from DOM
if (position == itemsCount)
sort_ul.append(li); // * if pos=last: append
else // else: insert before position-1
li.insertBefore($('#sortable li:eq('+(position - 1)+')'));
updateIndexes(); // * update items numbering
li.effect('slide'); // * apply 'slide' effect when in
}); // new position
}else{ li.effect('highlight'); } // * if invalid position: highlight
}}});
here is something that moves the li items around by changing the numbers:
function setOrder() {
$.each($('ul li input'), function(index, el) {
el.value = (index + 1);
});
}
setOrder();
$('ul li input').live('change', function() {
var change = (parseInt(this.value) - 1);
if(change > ($('ul li input').length - 1)){
change = $('ul li input').length - 1;
}
var index = $(this).index('ul li input');
var move = $('ul li')[change];
var arr = [];
$.each($('ul li'), function(ind, el) {
arr[ind] = $(this).clone();
})
arr[index] = move;
$('input', move).val(index + 1);
arr[change] = $(this).parent()[0];
arr.sort();
$('ul li').remove();
var indexAt = 0;
$.each(arr, function(index, el) {
$('ul').append(el);
});
setOrder();
})
$('ul').sortable({
stop: function(a, b) {
var arr = [];
var i = 0;
$.each($('ul li'), function(ind, el) {
arr[i] = $(this).clone();
i++;
})
$('ul li').remove();
$.each(arr, function(index, el) {
$('ul').append(el);
});
setOrder()
}
});
html:
<ul>
<li><input/>lijrfxgjh</li>
<li><input/>ghhgfhj</li>
<li><input/>lijrjh</li>
<li><input/>gfreydjgj</li>
<li><input/>rey</li>
<li><input/>gfjgf</li>
</ul>
fiddle: http://jsfiddle.net/maniator/bDvK8/
it is a bit glitchy, but it is a start

Categories

Resources