Cycling through a jQuery object with elements grouped together - javascript

I have a set of list items that contain nested lists, sort of like this:
<ul class="searchselectors">
<li class="group">Group name 1
<ul>
<li class="item selected">List item 1.1</li>
<li class="item">List item 1.2</li>
<li class="item">List item 1.3</li>
</ul>
</li>
<li class="group">Group name 2
<ul>
<li class="item">List item 2.1</li>
<li class="item">List item 2.2</li>
<li class="item">List item 2.3</li>
</ul>
</li>
<li class="group">Group name 3
<ul>
<li class="item">List item 3.1</li>
</ul>
</li>
</ul>
I want to cycle through all of the .item elements using up/down arrow keys (which I already have set up by using on('keydown') and catching key codes 38 and 40) and set .selected on the next item before or after the currently selected item, wrapping around to the top/bottom as necessary.
Using $().next() and $().prev() will not work, since it will only work on siblings, and not on a jQuery object such as $('.searchselectors .item').\

I was working on the same problem but in my project I'm using KnockoutJS. In fact, the original logic was written with pure jQuery and I refactored it with Knockout. Here's a solution for your problem using jQuery:
Fiddle - http://jsfiddle.net/6QN77/2/
I didn't spend too much time cleaning up the JavaScript, but I'm leaving that to you now.
HTML
<ul id="searchselectors">
<li class="group">Group name 1
<ul>
<li class="item selected">List item 1.1</li>
<li class="item">List item 1.2</li>
<li class="item">List item 1.3</li>
</ul>
</li>
<li class="group">Group name 2
<ul>
<li class="item">List item 2.1</li>
<li class="item">List item 2.2</li>
<li class="item">List item 2.3</li>
</ul>
</li>
<li class="group">Group name 3
<ul>
<li class="item">List item 3.1</li>
</ul>
</li>
</ul>
jQuery
$(function () {
var $menu = $("#searchselectors"),
$items = $menu.find(".item"),
$selectedItem = $menu.find(".selected"),
selectedIndex = $selectedItem.length - 1;
$(document).on("keydown", function (e) {
switch(e.keyCode) {
case 40: // down arrow
$selectedItem.removeClass("selected");
selectedIndex = (selectedIndex + 1) % $items.length;
$selectedItem = $items.eq(selectedIndex).addClass("selected");
break;
case 38: // up arrow
$selectedItem.removeClass("selected");
selectedIndex = (selectedIndex - 1) % $items.length;
$selectedItem = $items.eq(selectedIndex).addClass("selected");
break;
}
});
});
UPDATE: My solution revolves around getting a reference to a wrapper element (#searchselectors) and getting all the LI elements marked with the CSS class .item. Next I get a reference to the currently selected element and its index. Finally, the code listens to the down and up arrow keys being pressed (keydown), decrementing if going up and incrementing if going up. Cycling is achieved via the modulus operator. The selected item's CSS class is removed and put back. The selected item reference is used for performance reasons so I don't have to write $items.removeClass(".selected").eq(selectedIndex).addClass("selected");

In my quest to provide native JS answers to those looking for it, here is #Mario j Vargas' good answer adapted in native Javascript. It only takes 2 lines of extra code.
http://jsfiddle.net/kevinvanlierde/7tQSW/2/
Only putting the JS up here, HTML is the same.
(function () {
var $menu = document.getElementById('searchselectors'),
items = $menu.getElementsByClassName('item'),
$selectedItem = $menu.getElementsByClassName('selected')[0],
selectedIndex = Array.prototype.indexOf.call($selectedItem, items)+1;
document.body.addEventListener('keydown', function (e) {
switch(e.keyCode) {
case 40: // down arrow
$selectedItem.className = $selectedItem.className.replace(' selected','');
selectedIndex = selectedIndex < items.length - 1 ? selectedIndex + 1 : selectedIndex;
$selectedItem = items[selectedIndex];
$selectedItem.className += ' selected';
break;
case 38: // up arrow
$selectedItem.className = $selectedItem.className.replace(' selected','');
selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : selectedIndex;
$selectedItem = items[selectedIndex];
$selectedItem.className += ' selected';
break;
}
}, false);
}());

Easiest way to get all the list items with class "item" is:
var items = $('.item');
for (var i = 0; i < items.length; i++) {
var item = items[i]; // iterate
}
And then, you can select the next item from the list
OR
you can do this
if (!$().next) {
var nextUL= $().parent.find('ul')
iterateThruList(nextUL);
}

You could use something like
var UL = $(".searchselectors").children().length; //number of UL (group names)
to iterate through items.

Related

How to keep a menu-item selected in html with javascript

This is my html code. How can I keep a menu-item (link to another page) selected when I'am browsing ? I'd like to do it with javascript. Thank you in advance.
<ul class="header-menu" id="nav">
<li class="menu-item">HOME</li>
<li class="menu-item">NEWS</li>
<li class="menu-item">TOUR DATES</li>
<li class="menu-item">GALLERY</li>
<li class="menu-item">ABOUT</li>
</ul>
There are multiple ways to achieve that effect. Let's first state that you have an "active" class that you can use on the menu items that will make them pop out, how would you go about applying that class?
First of all, I would assign a specific class or id to all the menu items, to make them easy to reference within the css (or javascript).
Let's say that now your situation is like this:
<ul class="header-menu" id="nav">
<li class="menu-item home-item">HOME</li>
<li class="menu-item news-item">NEWS</li>
<li class="menu-item tour-item">TOUR DATES</li>
<li class="menu-item gallery-item">GALLERY</li>
<li class="menu-item about-item">ABOUT</li>
</ul>
Now, with javascript, you could do it like this:
// Get the page name
let pathArray = location.pathname.split("/");
let page = pathArray[pathArray.length-1];
// Get all menu items and convert them to an Array
let menuItems = document.querySelectorAll(".header-menu .menu-item");
menuItems = new Array(...menuItems);
let lookFor = "";
// Based on the page, set the variable lookFor as the identifying class
switch (page) {
case "home.html":
lookFor = "home-item";
break;
case "news.html":
lookFor = "news-item";
break;
// ...
}
// Get the element that contains the class
let item = menuItems.filter( (item) => item.classList.contains(lookFor) )[0];
// Set the "active" class on the element
item.classList.add("active");
Here you can check out a codesandbox with the working code.

append / appendChild not working on all items

I'm trying to move all the list items from an list to another using only javascript but for some reason only half of them are actually moved.
Heres a working example of what I'm doing:
var results_ul = document.getElementById('results');
var stores_li = document.getElementsByClassName('store-list-item');
for (var x = 0; x < stores_li.length; x++) {
document.getElementById('hide').appendChild(stores_li[x]);
stores_li[x].className += ' teste';
}
<p>results</p>
<ul id="results">
<li class="store-list-item">Teste 1</li>
<li class="store-list-item">Teste 2</li>
<li class="store-list-item">Teste 3</li>
<li class="store-list-item">Teste 4</li>
</ul>
<p>Hide:</p>
<ul id="hide"></ul>
What seems to be the problem?
getElementsByClassName returns a live list.
When you append the element to a different element, you change its position in the list.
So it starts off as:
1 2 3 4
Then you move the first one:
2 3 4 1
Then you access the second one … but the second one is now 3 because everything has shuffled down the list.
You could copy each element into an array (which will not be a live list) and then iterate over that array to move them (so they won't change positions as you go).
Alternatively, you could use querySelectorAll which returns a non-live list.
You should better use querySelectorAll than getElementsByClassName
var results_ul = document.getElementById('results');
var stores_li = document.querySelectorAll('.store-list-item');
stores_li.forEach((item)=>{
document.getElementById('hide').appendChild(item);
item.className += ' teste';
});
<p>results</p>
<ul id="results">
<li class="store-list-item">Teste 1</li>
<li class="store-list-item">Teste 2</li>
<li class="store-list-item">Teste 3</li>
<li class="store-list-item">Teste 4</li>
</ul>
<p>Hide:</p>
<ul id="hide"></ul>
Try use querySelectorAll . It'll returns a non-live list. That's what you need.
var stores_li = document.querySelectorAll('.store-list-item');
To increase more information:
Live : when the changes in the DOM are reflected in the collection. The content suffers the change when a node is modified.
Non-Live : when any change in the DOM does not affect the content of the collection.
document.getElementsByClassName() is an HTMLCollection, and is live.
document.querySelectorAll() is a NodeList and is not live.
In your code you are removing each element from the first list and inserting into the new list. After you remove 2 elements it will have only 2 elements in the first list but now you are searching the 3 rd index in the loop which is not there. So to make it work i have prepended each element from the last.
var results_ul = document.getElementById('results');
var stores_li = document.getElementsByClassName('store-list-item');
var hide_ul = document.getElementById('hide');
for (var x = 0, y = stores_li.length; x < y; x++) {
hide_ul.insertBefore(stores_li[y-x-1],hide_ul.firstChild);
stores_li[x].className += ' teste';
}
<p>results</p>
<ul id="results">
<li class="store-list-item">Teste 1</li>
<li class="store-list-item">Teste 2</li>
<li class="store-list-item">Teste 3</li>
<li class="store-list-item">Teste 4</li>
</ul>
<p>Hide:</p>
<ul id="hide"></ul>
Or you may want to clone the element with Jquery and you can push into the clonned ones then delete the orginals from top. I could not find any equivalent of clone() for js but if you want to check link is here
var results_ul = document.getElementById('results');
var stores_li = document.getElementsByClassName('store-list-item');
while(stores_li.length>0) {
document.getElementById('hide').appendChild(stores_li[0]);
stores_li[x].className += ' teste';
}

Traversing the Ordered List backwards returning each li text

How can I traverse an ordered list and return the text if I have a scenario where the user can click on a li element like Cat 1-2 and it returns all of the parent li's text into a string or an array. If an array I can reverse the sort but eventually I need it to be a string.
Example:
<ul>
<li>Cat 1
<ul>
<li>Cat 1-1
<ul>
<li>Cat 1-2</li>
</ul>
</li>
</ul>
</li>
<li>Cat 2
<ul>
<li>Cat 2-1
<ul>
<li>Cat 2-2</li>
</ul>
</li>
</ul>
</li>
</ul>
if clicked on Cat 1-2 the desired result would be:
str = "Cat 1/Cat 1-1/Cat 1-2";
if clicked on Cat 2-1 the desired result would be:
str = "Cat 2/Cat 2-1";
What I would like to have is checkboxes on this where I could join all the selections into a string hierarchy like:
str = "Cat 1/Cat 1-1/Cat 1-2|Cat 2/Cat 2-1";
Here; I'll show a down and dirty method to get you rolling, then you can find a better way (maybe using textContent)...
$('li').click(function(e){
var parents = $(this).add($(this).parents('li'))
.map(function(){
return $(this).clone().children().remove().end()
.text().replace(/\r|\n|^\s+|\s+$/g,'');
})
.toArray().join('/');
alert(parents);
e.stopPropagation();
});
I don't know if this is any more efficient than Brad's method, but I started working on this earlier and it bugged me until I had it finished.
jsFiddle example
var ary = [];
$('li').click(function (e) {
ary.push($.trim($(this).clone()
.children()
.remove()
.end()
.text()));
if ($(this).parents('ul').parent('li').length == 0) {
console.log(ary.reverse().join('/'));
ary = [];
}
});

Sort and separate a set of list elements using JavaScript/jQuery

I have a question
Sort the list (you can use default JS/jquery sorting functions )
Break the sorted list apart into different sub-lists with a maximum of 'x' items each, 'x' being a parameter you pass in. The above
sample result assumes x=2
<ul>
<li> 4 </li>
<li> 1 </li>
<li> 7 </li>
<li> 5 </li>
<li> 3 </li>
</ul>
Write a function to convert that to
<ul>
<li> 1 </li>
<li> 3 </li>
</ul>
<ul>
<li> 4 </li>
<li> 5 </li>
</ul>
<ul>
<li> 7 </li>
</ul>
Feel free to use any libraries/references you like within reason (i.e., don't use a library which has a "splitList" function). The key is to do this as efficiently as possible in terms of DOM manipulation.
i solved this question by creating separate list and deleted the original but I am wondering how can we do it by only modifying the existing one.(I mean modify on the fly while traversing)
html first:
<ul id="list">
<li> 4 </li>
<li> 1 </li>
<li> 7 </li>
<li> 5 </li>
<li> 3 </li>
</ul>
<div id="container"></div>
javascript(jquery):
function sortText(a,b){
return $(a).text().trim() > $(b).text().trim() ? 1 : -1;
};
var ul = $('#list');
var elements = ul.find('li').detach();
var i=2;
var lastul;
var container = $('#container');
elements.sort(sortText).each(function(index){
if (index % i === 0) {
container.append(lastul);
lastul = $('<ul></ul>');
}
lastul.append(elements[index]);
})
container.append(lastul);
ul.remove();
var optionTexts = [];
$("ul li").each(function() { optionTexts.push($(this).text()) });
optionTexts.sort();
//alert(optionTexts.length);
var splityby = 2;//change this value how you want to split
var itmes= parseInt(optionTexts.length/splityby);
var remaining = optionTexts.length%splityby;
//alert(itmes+'and'+remaining);
var st='';
var i=0;
for(k=0;k<itmes+remaining;k++){
st+='<ul>';
for(j=0;j<splityby;j++){
if(i<optionTexts.length){
st+='<li>'+optionTexts[i++] +'</li>' ;
}
}
st+='</ul>';
}
$('#hi').append(st);
html
<div id="hi"></div>
<ul> <li> 4 </li> <li> 1 </li> <li> 7 </li> <li> 5 </li> <li> 3 </li> </ul>
The most efficient method to sort is by using the native Array.sort method (jQuery().sort implements the Array.sort). Fiddle: http://jsfiddle.net/RJEJQ/1/.
The code can become even more efficient by getting rid of jQuery, and using document.createElement() and ordinary for() loops.
var originalUl = $('ul');
var listElements = originalUl.children('li'); //List
listElements.sort(function(x, y){
return parseInt(x.textContent, 10) - parseInt(y.textContent);
});
//Sorted by number, 1, 2, 3, ...
var newList = $(""); //Placeholder
listElements.each(function(i){
if(i%2 == 0){ //If even, a new list has to be created
originalUl.before(newList);
newList = $("<ul>"); //Create new list
}
newList.append(this);
});
if(newList.length) { // If there are any remaining list elements in the holder.
originalUl.before(newList);
}
originalUl.remove(); //Remove original, empty ul.
As seen at this demo, the result looks like:
ul
li 1
li 3
ul
li 4
li 5
ul
li 7
This partially uses an answer I wrote before that divides elements into groups, with the addition of sorting them first:
Working demo: http://jsfiddle.net/AndyE/QVRRn/
var i = 0,
ul = $("ul"),
lis = ul.children().detach(),
group;
// Sort the elements
lis.sort(function (a, b) {
return $.text(a).localeCompare($.text(b));
});
// Wrap the elements
while ((group = lis.slice(i, i += 2)).length)
group.wrapAll('<ul></ul>');
// Replace the original UL element
ul.replaceWith(lis.closest("ul"));
It's important to detach the <li> elements from the document before manipulating them, this will make the operation much faster on large sets.
If you must have to manipulate DOM, I believe your question was answered.
But...
DOM manipulation is slow.
Concatenate strings also.
The sort function was taken from here: How may I sort a list alphabetically using jQuery?
Live demo:
http://jsfiddle.net/gknjQ/1/

Detecting "runs" of DOM elements in jQuery

What is the best way to detect runs of dom elements in jQuery?
For instance, if I have the following list of items
<ol>
<li class="a"></li>
<li class="foo"></li>
<li class="a"></li>
<li class="a"></li>
<li class="foo"></li>
<li class="foo"></li>
<li class="foo"></li>
<li class="a"></li>
<li class="foo"></li>
<li class="foo"></li>
<li class="foo"></li>
</ol>
Say I want to grab all the li.foo elements and wrap them inside their own <ol> block (or any wrapper for that matter) to end up with something like.
<ol>
<li class="a"></li>
<li class="foo"></li>
<li class="a"></li>
<li class="a"></li>
<li><ol>
<li class="foo"></li>
<li class="foo"></li>
<li class="foo"></li>
</ol></li>
<li class="a"></li>
<li><ol>
<li class="foo"></li>
<li class="foo"></li>
<li class="foo"></li>
</ol></li>
</ol>
As you can see from the example, I only want to wrap "runs" of li.foo dom elements (where there are 2 or more li.foo elements in succession.
I'm not sure of the best/most efficient way to accomplish this via jQuery (or just plain javascript for that matter).
Example: http://jsfiddle.net/kNfxs/1/
$('ol .foo').each(function() {
var $th = $(this);
var nextUn = $th.nextUntil(':not(.foo)');
if(!$th.prev('.foo').length && nextUn.length)
nextUn.andSelf().wrapAll('<li><ol></ol></li>');
});
Loop over the .foo elements, and if the previous element is not .foo, and it has at least 1 .foo after it, then grab all the next .foo elements using the nextUntil()(docs) method and include the original using the andSelf()(docs) method, then wrap them using the wrapAll()(docs) method.
Update: This will be a little more efficient because it avoids the nextUntil()(docs) method when there's a previous .foo().
Example: http://jsfiddle.net/kNfxs/2/
$('ol .foo').each(function() {
var $th = $(this);
if($th.prev('.foo').length) return; // return if we're not first in the group
var nextUn = $th.nextUntil(':not(.foo)');
if( nextUn.length)
nextUn.andSelf().wrapAll('<li><ol></ol></li>');
});
Use something like this:
$(li).each(function(){
if($(this).next().hasClass('foo')){
---- Recursively check until the end of the run has been found ----
}
});
To recursively check write a function that checks the next element until the end of the run has been found.
Not sure how well this works for performance:
var $foo = $('.foo + .foo');
$foo.add($foo.prev());
$foo will be the set of ".foo runs"
Edit to add:
I thought of a simpler way:
var $foo = $('.foo + .foo').prev('.foo').andSelf();
Working example: http://jsfiddle.net/v8GY8/
For posterity:
// Takes a jQuery collection and returns an array of arrays of contiguous elems
function groupContiguousElements( $elems ){
var groups = [];
var current, lastElement;
$elems.each(function(){
if ($(this).prev()[0] == lastElement ){
if (!current) groups.push( current=[lastElement] );
current.push( this );
}else{
current = null;
}
lastElement = this;
});
return groups;
}
var groups = groupContiguousElements( $('li.foo') );
$.each( groups, function(){
var wrapper = $('<ol>').insertBefore(this[0]);
$.each(this,function(){
wrapper.append(this);
});
});

Categories