YUI 3 drag and drop with Constraints - javascript

I am new to YUI. I am wanting to achieve a drag and drop operation with contstraints. I am following the simple YUI 3 guide and was able to achieve the drag and drop according to the code they given which is.
http://yuilibrary.com/yui/docs/dd/scroll-list.html
HTML
<body>
<div id="demo">
<ul id="list1">
<li class="list1">Item #1</li>
<li class="list1">Item #2</li>
<li class="list1">Item #3</li>
<li class="list1">Item #4</li>
<li class="list1">Item #5</li>
<li class="list1">Item #6</li>
<li class="list1">Item #7</li>
<li class="list1">Item #8</li>
<li class="list1">Item #9</li>
<li class="list1">Item #10</li>
<li class="list1">Item #11</li>
<li class="list1">Item #12</li>
</ul>
<ul id="list2">
<li class="list2">Item #1</li>
<li class="list2">Item #2</li>
<li class="list2">Item #3</li>
<li class="list2">Item #4</li>
<li class="list2">Item #5</li>
<li class="list2">Item #6</li>
<li class="list2">Item #7</li>
<li class="list2">Item #8</li>
<li class="list2">Item #9</li>
<li class="list2">Item #10</li>
<li class="list2">Item #11</li>
<li class="list2">Item #12</li>
</ul>
</div>
CSS
yui3-dd-proxy {
text-align: left;
}
#demo {
width: 600px;
}
#demo {
border: 1px solid black;
padding: 10px;
margin: 10px;
zoom: 1;
}
#demo ul li {
border: 1px solid black;
background-color: #8DD5E7;
cursor: move;
margin: 3px;
list-style-type: none;
}
#demo:after { display: block; clear: both; visibility: hidden; content: '.'; height: 0;}
#demo ul {
border: 1px solid black;
margin: 10px;
width: 200px;
height: 400px;
float: left;
padding: 0;
zoom: 1;
position: relative;
overflow: auto;
}
#demo ul li.list1 {
background-color: #8DD5E7;
border:1px solid #004C6D;
}
#demo ul li.list2 {
background-color: #EDFF9F;
border:1px solid #CDCDCD;
}
Javascript
YUI().use('dd-constrain', 'dd-proxy', 'dd-drop', 'dd-scroll', function(Y) {
//Listen for all drop:over events
//Y.DD.DDM._debugShim = true;
Y.DD.DDM.on('drop:over', function(e) {
//Get a reference to our drag and drop nodes
var drag = e.drag.get('node'),
drop = e.drop.get('node');
//Are we dropping on a li node?
if (drop.get('tagName').toLowerCase() === 'li') {
//Are we not going up?
if (!goingUp) {
drop = drop.get('nextSibling');
}
//Add the node to this list
e.drop.get('node').get('parentNode').insertBefore(drag, drop);
//Set the new parentScroll on the nodescroll plugin
e.drag.nodescroll.set('parentScroll', e.drop.get('node').get('parentNode'));
//Resize this nodes shim, so we can drop on it later.
e.drop.sizeShim();
}
});
//Listen for all drag:drag events
Y.DD.DDM.on('drag:drag', function(e) {
//Get the last y point
var y = e.target.lastXY[1];
//is it greater than the lastY var?
if (y < lastY) {
//We are going up
goingUp = true;
} else {
//We are going down.
goingUp = false;
}
//Cache for next check
lastY = y;
Y.DD.DDM.syncActiveShims(true);
});
//Listen for all drag:start events
Y.DD.DDM.on('drag:start', function(e) {
//Get our drag object
var drag = e.target;
//Set some styles here
drag.get('node').setStyle('opacity', '.25');
drag.get('dragNode').set('innerHTML', drag.get('node').get('innerHTML'));
drag.get('dragNode').setStyles({
opacity: '.5',
borderColor: drag.get('node').getStyle('borderColor'),
backgroundColor: drag.get('node').getStyle('backgroundColor')
});
});
//Listen for a drag:end events
Y.DD.DDM.on('drag:end', function(e) {
var drag = e.target;
//Put our styles back
drag.get('node').setStyles({
visibility: '',
opacity: '1'
});
});
//Listen for all drag:drophit events
Y.DD.DDM.on('drag:drophit', function(e) {
var drop = e.drop.get('node'),
drag = e.drag.get('node');
//if we are not on an li, we must have been dropped on a ul
if (drop.get('tagName').toLowerCase() !== 'li') {
if (!drop.contains(drag)) {
drop.appendChild(drag);
//Set the new parentScroll on the nodescroll plugin
e.drag.nodescroll.set('parentScroll', e.drop.get('node'));
}
}
});
//Static Vars
var goingUp = false, lastY = 0;
//Get the list of li's in the lists and make them draggable
var lis = Y.all('#demo ul li');
lis.each(function(v, k) {
var dd = new Y.DD.Drag({
node: v,
target: {
padding: '0 0 0 20'
}
}).plug(Y.Plugin.DDProxy, {
moveOnEnd: false
}).plug(Y.Plugin.DDConstrained, {
constrain2node: '#demo'
}).plug(Y.Plugin.DDNodeScroll, {
node: v.get('parentNode')
});
});
Y.one('#make').on('click', function(e) {
YUI().use('dd-drag', 'dd-proxy', function(Y) {
//Selector of the node to make draggable
var dd = new Y.DD.Drag({
container: '#demo',
node: 'li'
}).plug(Y.Plugin.DDProxy); //This config option makes the node a Proxy Drag
var demo =Y.one('#demo ul');
for (var i = 1; i < 11; i++) {
//demo.append('<li class="list3">New item #' + i + '</i><br>');
demo.append('<li class="list3">Item #' + i + '</li>' )
}
})
});
//Create simple targets for the 2 lists.
var uls = Y.all('#demo ul');
uls.each(function(v, k) {
var tar = new Y.DD.Drop({
node: v
});
});
});
YUI().use('dd-delegate', 'dd-drop-plugin', 'dd-constrain', 'dd-proxy', function(Y) {
var del = new Y.DD.Delegate({
container: '#demo',
nodes: 'li'
});
del.on('drag:start', function(e) {
e.target.get('node').setStyle('opacity', '.5');
});
del.on('drag:end', function(e) {
e.target.get('node').setStyle('opacity', '1');
});
del.dd.plug(Y.Plugin.DDConstrained, {
constrain2node: '#play'
});
del.dd.plug(Y.Plugin.DDProxy, {
moveOnEnd: false,
cloneNode: true
});
var drop = Y.one('#drop').plug(Y.Plugin.Drop);
drop.drop.on('drop:hit', function(e) {
drop.set('innerHTML', 'You dropped: <strong>' + e.drag.get('node').get('innerHTML') + '</strong>');
});
});
I would like to Contrain the left drag meaning when i drag the blue over to the yellow. I would like to repopulate the blue item once it is dropped in the yellow area. The YUI guide has something similar to what I want to achieve here:
http://yuilibrary.com/yui/docs/dd/delegate-plugins.html
I am not quite clear on how to implement these two operations together to achieve the effect I need.
Any help would be good.
thanks
Javascript
YUI().use('dd-delegate', 'dd-drop-plugin', 'dd-constrain', 'dd-proxy', function(Y) {
var del = new Y.DD.Delegate({
container: '#demo',
nodes: 'li'
});
del.on('drag:start', function(e) {
e.target.get('node').setStyle('opacity', '.5');
});
del.on('drag:end', function(e) {
e.target.get('node').setStyle('opacity', '1');
});
del.dd.plug(Y.Plugin.DDConstrained, {
constrain2node: '#play'
});
del.dd.plug(Y.Plugin.DDProxy, {
moveOnEnd: false,
cloneNode: true
});
var drop = Y.one('#drop').plug(Y.Plugin.Drop);
drop.drop.on('drop:hit', function(e) {
drop.set('innerHTML', 'You dropped: <strong>' + e.drag.get('node').get('innerHTML') + '</strong>');
});
});

Related

how do i change the color one by one to the items there with each click so that the previous one turns green again?

<button>Click!</button>
<ul>
<li class="green">Home</li>
<li class="green">faq</li>
<li class="green">dropdown</li>
<li class="green">about</li>
<li class="green">contact</li>
</ul>
let li = document.querySelectorAll('li');
let btn = document.querySelector('button');
for(let i=0; i<li.length; i++) {
let number = 0;
btn.addEventListener('click', ()=>{
li[number++].classList.add('red')
if(number === li.length) {
number = 0
}
})
}
I wanted a single item to turn red with each click and the previous one to turn green again
You can do it like this if this helps you. As soon as you press the button. Remove the red class from every element first and then add it like you were doing
let li = document.querySelectorAll('li');
let btn = document.querySelector('button');
for(let i=0; i<li.length; i++) {
let number = 0;
btn.addEventListener('click', ()=>{
for(let i=0; i<li.length; i++) {
li[i].classList.remove('red')
}
li[number++].classList.add('red')
if(number === li.length) {
number = 0
}
})
}
.green {
color:green;
}
.red {
color:red;
}
<button>Click!</button>
<ul>
<li class="green">Home</li>
<li class="green">faq</li>
<li class="green">dropdown</li>
<li class="green">about</li>
<li class="green">contact</li>
</ul>
Doing this with JavaScript and one event listener
document.querySelector(".menu").addEventListener("click", function (e) {
// find the li that was clicked
const clickedLi = e.target.closest("li");
if (!clickedLi) return;
// see if we had something clicked already
const selected = e.currentTarget.querySelector(".red");
if (selected) selected.classList.remove('red');
// update the class on what was clicked
clickedLi.classList.add('red');
});
.green {
background-color: green;
}
li.red {
background-color: red;
}
<ul class="menu">
<li class="green">Home</li>
<li class="green">faq</li>
<li class="green">dropdown</li>
<li class="green">about</li>
<li class="green">contact</li>
</ul>
Using just html and css to make the selections
.menu input[type="radio"] {
display: none;
}
.menu input[type="radio"]+label {
display: inline-block;
width: 100%;
background-color: green;
}
.menu input[type="radio"]:checked + label {
background-color: red;
}
<ul class="menu">
<li><input type="radio" name="list" id="li1"><label for="li1">Foo</label></li>
<li><input type="radio" name="list" id="li2"><label for="li2">Bar</label></li>
<li><input type="radio" name="list" id="li3"><label for="li3">Baz</label></li>
<li><input type="radio" name="list" id="li4"><label for="li4">Cheese</label></li>
</ul>

Sortable js change array based on dragged element

I have a list of tasks, i want to be able to drag them around and get the sortOrder array to change to the new order, this is what I've come up with but it's not working right, sometimes i get the order, sometimes i don't.. for example if i drag the first element to second position it works, but if i drag to last position it's not... also if i drag up it usually wrong.. What am i doing wrong? or can this be done some other way? I need to keep track of previous/next id's because there can be other elements in the sortOrder that are not visible, so i need to add the dragged element before or after a visible element.
Thanks
const sortOrder = ["7","x", "5","y", "55", "1"],
tasks = document.getElementById("tasks");
Sortable.create(tasks, {
scroll: true,
scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling.
scrollSpeed: 10, // px, speed of the scrolling
bubbleScroll: true, // apply autoscroll to all parent elements, allowing for easier movement
revertOnSpill: true,
group: 'shared',
animation: 0,
dataIdAttr: 'id',
ghostClass: 'task-ghost',
dragClass: 'task-drag',
onEnd: (evt) => {
// let newIndex;
console.log('previousElementSibling', evt.item.previousElementSibling);
console.log('nextElementSiblingElementSibling', evt.item.nextElementSiblingElementSibling);
console.log('oldIndex', evt.oldIndex);
console.log('newIndex', evt.newIndex);
let neighborIndex;
// drag up or down
if (evt.oldIndex < evt.newIndex) neighborIndex = sortOrder.indexOf(evt.item.previousElementSibling?.id || sortOrder[0]);
else neighborIndex = sortOrder.indexOf(evt.item.nextElementSibling?.id);
console.log("neighborIndex",neighborIndex);
// remove element from array
sortOrder.splice(sortOrder.indexOf(evt.item.id), 1);
// add element to specific position
sortOrder.splice(neighborIndex, 0, evt.item.id);
console.log(sortOrder);
}
})
.tasks {
list-style-type: none;
}
li {
border: solid 1px red;
margin: 4px;
width: 200px;
}
.task-ghost{ opacity: 0; }
.task-drag{ opacity: 1;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.14.0/Sortable.min.js"></script>
<ul class="tasks" id="tasks">
<li id="7" class="task">element 7</li>
<li id="5" class="task">element 5</li>
<li id="55" class="task">element 55</li>
<li id="1" class="task">element 1</li>
</ul>
I've managed to get good results, if someone has a better way please tell me.
const sortOrder = ["7", "x", "5", "y", "55", "1"],
tasks = document.getElementById("tasks");
Sortable.create(tasks, {
scroll: true,
scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling.
scrollSpeed: 10, // px, speed of the scrolling
bubbleScroll: true, // apply autoscroll to all parent elements, allowing for easier movement
revertOnSpill: true,
group: 'shared',
animation: 0,
dataIdAttr: 'id',
ghostClass: 'task-ghost',
dragClass: 'task-drag',
onEnd: (evt) => {
// let newIndex;
console.log('previousElementSibling', evt.item.previousElementSibling);
console.log('nextElementSiblingElementSibling', evt.item.nextElementSiblingElementSibling);
console.log('oldIndex', evt.oldIndex);
console.log('newIndex', evt.newIndex);
let neighborIndex;
sortOrder.splice(sortOrder.indexOf(evt.item.id), 1); // stergem pe ala pe care l-am tras de sus
if (evt.oldIndex < evt.newIndex) neighborIndex = sortOrder.indexOf(evt.item.previousElementSibling.id) + 1;
else neighborIndex = sortOrder.indexOf(evt.item.nextElementSibling.id);
sortOrder.splice(neighborIndex, 0, evt.item.id); // il adaugam dupa vecin
console.log(sortOrder);
}
})
.tasks {
list-style-type: none;
}
li {
border: solid 1px red;
margin: 4px;
width: 200px;
}
.task-ghost {
opacity: 0;
}
.task-drag {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.14.0/Sortable.min.js"></script>
<ul class="tasks" id="tasks">
<li id="7" class="task">element 7</li>
<li id="5" class="task">element 5</li>
<li id="55" class="task">element 55</li>
<li id="1" class="task">element 1</li>
</ul>

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.

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

Categories

Resources