How to randomly sort list items? - javascript

I currently have this code that randomly sorts list items:
var $ul = $('#some-ul-id');
$('li', $ul).sort(function(){
return ( Math.round( Math.random() ) - 0.5 )
}).appendTo($ul);
However, is there any better solution for that?

Look at this question and answer thread. I like this solution via the user gruppler:
$.fn.randomize = function(selector){
var $elems = selector ? $(this).find(selector) : $(this).children(),
$parents = $elems.parent();
$parents.each(function(){
$(this).children(selector).sort(function(){
return Math.round(Math.random()) - 0.5;
// }). remove().appendTo(this); // 2014-05-24: Removed `random` but leaving for reference. See notes under 'ANOTHER EDIT'
}).detach().appendTo(this);
});
return this;
};
EDIT: Usage instructions below.
To randomize all <li> elements within each '.member' <div>:
$('.member').randomize('li');
To randomize all children of each <ul>:
$('ul').randomize();
ANOTHER EDIT: akalata has let me know in the comments that detach() can be used instead of remove() with the main benefit being if any data or attached listeners are connected to an element and they are randomized, detach() will keep them in place. remove() would just toss the listeners out.

I also stuck to such questions I search on google and come across one code. I modify this code for my uses. I also include the shuffle the list after 15 seconds.
<script>
// This code helps to shuffle the li ...
(function($){
$.fn.shuffle = function() {
var elements = this.get()
var copy = [].concat(elements)
var shuffled = []
var placeholders = []
// Shuffle the element array
while (copy.length) {
var rand = Math.floor(Math.random() * copy.length)
var element = copy.splice(rand,1)[0]
shuffled.push(element)
}
// replace all elements with a plcaceholder
for (var i = 0; i < elements.length; i++) {
var placeholder = document.createTextNode('')
findAndReplace(elements[i], placeholder)
placeholders.push(placeholder)
}
// replace the placeholders with the shuffled elements
for (var i = 0; i < elements.length; i++) {
findAndReplace(placeholders[i], shuffled[i])
}
return $(shuffled)
}
function findAndReplace(find, replace) {
find.parentNode.replaceChild(replace, find)
}
})(jQuery);
// I am displying the 6 elements currently rest elements are hide.
function listsort(){
jQuery('.listify_widget_recent_listings ul.job_listings').each(function(index){
jQuery(this).find('li').shuffle();
jQuery(this).find('li').each(function(index){
jQuery(this).show();
if(index>=6){
jQuery(this).hide();
}
});
});
}
// first time call to function ...
listsort();
// calling the function after the 15seconds..
window.setInterval(function(){
listsort();
/// call your function here 5 seconds.
}, 15000);
</script>
Hope this solution helps....Have a great working time ..

Related

Show a specific number of random objects from a selection and hide all others with js/jQuery?

What I did so far was the following:
function randomSelectObjects(randObjects, countShow){
var i = 0;
var countRandObjects = randObjects.length;
var preselectedObj = false;
randObjects.hide(); // hide all items
while (i < countShow) { // while until we found enough items we can show
preselectedObj = randObjects.eq(Math.floor(Math.random()*countRandObjects)); // random select an object
if(preselectedObj.is(':hidden')){ // make sure it is not already unhidden
preselectedObj.show(); // show the object
i++; // up the counter – done only in case it was not already visible
}
}
}
Usage:
var randObjects = $('.items');
randomSelectObjects(randObjects, 1);
The problem is that I will run into selecting an already revealed (show()) item inside while from time to time. I would love to remove that unnecessary overhead.
Unfortunately there seems to be no way to remove an object from a cached selection. remove() also removes the object from the DOM which is not (always) what I want.
Cloning the selection of objects first and then using remove() would work for the selection process but then there would be the overhead to match the selected items with the live DOM for actually show() them.
My suggestion is create a unique random array first. Hide all elements then loop through the array of random inidices and show matching elements
// wrap in simple jQuery plugin
$.fn.randomDisplay = function(max_items) {
max_items = max_items || 5;
//create array of unique random indices
var randArr = randArray(this.length, max_items);
// hide all then filter matches to show
this.hide().filter(function(i){
return randArr.indexOf(i) >-1
}).show();
// creates unique array
function randArray(max, len) {
var arr = [], rand;
for (var i = 0; i < len; i++) {
rand = getRand(max)
while (arr.indexOf(rand) > -1) {
rand = getRand(max)
}
arr.push(rand);
}
return arr;
}
// random number helper
function getRand(max) {
return Math.floor(Math.random() * max)
}
}
// use
$(function(){
$('.item').randomDisplay(7)
})
DEMO

Using querySelectorAll to get ALL elements with that class name, not only the first

I've ditched jquery about 9(ish) months ago and needed a selector engine (without all the hassle and don't mind ie<7 support) so i made a simplified version of document.querySelectorAll by creating this function:
// "qsa" stands for: "querySelectorAll"
window.qsa = function (el) {
var result = document.querySelectorAll(el)[0];
return result;
};
This works perfectly fine for 95% of the time but I've had this problem for a while now and i have researched mdn, w3c, SO and not to forget Google :) but have not yet found the answer as to why I only get the first element with the requested class.
And I know that only the first element being returned is caused by the "[0]" at the end, but the function won't work if I remove it so I've tried to make a for loop with an index variable that increases in value depending on the length of elements with that class like this:
window.qsa = function (el) {
var result, el = document.querySelectorAll(el);
for(var i = 0; i < el.length; ++i) {
result = el[i];
}
return result;
};
Again that did not work so I tried a while loop like this:
window.qsa = function (el) {
var result, i = 0, el = document.querySelectorAll(el);
while(i < el.length) {
i++;
}
result = el[i];
return result;
};
By now I'm starting to wonder if anything works? and I'm getting very frustrated with document.querySelectorAll...
But my stubborn inner-self keeps going and I keep on failing (tiering cycle) so I know that now is REALLY the time to ask these questions :
Why is it only returning the first element with that class and not all of them?
Why does my for loop fail?
Why does my while loop fail?
And thank you because any / all help is much appreciated.
Why is it only returning the first element with that class and not all of them?
Because you explicitly get the first element off the results and return that.
Why does my for loop fail?
Because you overwrite result with a new value each time you go around the end of loop. Then you return the last thing you get.
Why does my while loop fail?
The same reason.
If you want all the elements, then you just get the result of running the function:
return document.querySelectorAll(el)
That will give you a NodeList object containing all the elements.
Now that does what you say you want, I'm going to speculate about what your real problem is (i.e. why you think it doesn't work).
You haven't shown us what you do with the result of running that function, but my guess is that you are trying to treat it like an element.
It isn't an element. It is a NodeList, which is like an array.
If you wanted to, for instance, change the background colour of an element you could do this:
element.style.backgroundColor = "red";
If you want to change the background colour of every element in a NodeList, then you have to change the background colour of each one in turn: with a loop.
for (var i = 0; i < node_list.length; i++) {
var element = node_list[i];
element.style.backgroundColor = "red";
}
You are returning a single element. You can return the array. If you want to be able to act on all elements at once, jQuery style, you can pass a callback into your function;
window.qsa = function(query, callback) {
var els = document.querySelectorAll(query);
if (typeof callback == 'function') {
for (var i = 0; i < els.length; ++i) {
callback.call(els[i], els[i], i);
}
}
return els;
};
qsa('button.change-all', function(btn) {
// You can reference the element using the first parameter
btn.addEventListener('click', function(){
qsa('p', function(p, index){
// Or you can reference the element using `this`
this.innerHTML = 'Changed ' + index;
});
});
});
qsa('button.change-second', function(btn) {
btn.addEventListener('click', function(){
var second = qsa('p')[1];
second.innerHTML = 'Changed just the second one';
});
});
<p>One</p>
<p>Two</p>
<p>Three</p>
<button class='change-all'>Change Paragraphs</button>
<button class='change-second'>Change Second Paragraph</button>
Then you can call either use the callback
qsa('P', function(){
this.innerHTML = 'test';
});
Or you can use the array that is returned
var pList = qsa('p');
var p1 = pList[0];
This loop
for(var i = 0; i < el.length; ++i) {
result = el[i];
}
overwrites your result variable every time. That's why you always get only one element.
You can use the result outside though, and iterate through it. Kinda like
var result = window.qsa(el)
for(var i = 0; i < result.length; ++i) {
var workOn = result[i];
// Do something with workOn
}

Looping through objects in an array JS

I'm putting together this script which pulls two child elements from a containing div #mini_ads, adds them to an array. I want to be able to use the array to select them via index in order to manip. them individually.
I know I can just select them w/o even using an array of course, but I want this array as I may add multiple more elements later.
The issue is that I am not able to select the items individually by their index in the array. The current script I've got going is selecting and manipulating both objects in the array as if they're both index[0].
var miniAds = $('#mini_ads');
var elements = miniAds.children();
var changeWtime;
var adsArr = new Array();
var i = 0;
var x = 0;
adsArr.push(elements);
console.log(adsArr);
adsArr[i].css("display", "none");
var changeWtime = setInterval(function () {
for (x; x < 1; x++) {
return x;
while (x > i) {
adsArr[1].css("display", "block");
}
};
}, 5000);
console.log(x);
changeWtime;
I am not sure where I'm going wrong here. Assistance will be much appreciated. Thanks in advance.
Issues with your code
You're creating a double array when you push elements into 'adsArr':
adsArr.push(elements);
You're throwing a return statement in the for loop:
for (x; x < 1; x++ ){
return x;
// ...
You have a double loop for no reason while inside of the for.
Solution
I was going to explain the solution to this verbally, but after coding an example I realized that there is too much to explain this is another solution similar to yours:
var miniAds = $('#mini_ads'),
elements = miniAds.children(),
i = 2,
x = 0;
elements.hide();
var changeWtime = setInterval(function () {
if ( x < i ) {
$(elements[x]).show();
}
x++;
}, 5000);
Link to example on jsbin.
Hi u should push child divs as below function does and after that i believe u can perform ur task...
var adsArr= [];
$('#mini_ads').children().each(
function(i){
adsArr.push(this);
});
In plain Javascript use .styles()
.css() which is a JQuery method but not Javascript
ref http://www.w3schools.com/js/js_htmldom_css.asp

Swapping elements in a KnockoutJS observable array [duplicate]

I have a button that moves an item one position left in an observableArray. I am doing it the following way. However, the drawback is that categories()[index] gets removed from the array, thus discarding whatever DOM manipulation (by jQuery validation in my case) on that node.
Is there a way to swap two items without using a temporary variable so as to preserve the DOM node?
moveUp: function (category) {
var categories = viewModel.categories;
var length = categories().length;
var index = categories.indexOf(category);
var insertIndex = (index + length - 1) % length;
categories.splice(index, 1);
categories.splice(insertIndex, 0, category);
$categories.trigger("create");
}
Here's my version of moveUp that does the swap in one step:
moveUp: function(category) {
var i = categories.indexOf(category);
if (i >= 1) {
var array = categories();
categories.splice(i-1, 2, array[i], array[i-1]);
}
}
That still doesn't solve the problem, though, because Knockout will still see the swap as a delete and add action. There's an open issue for Knockout to support moving items, though. Update: As of version 2.2.0, Knockout does recognize moved items and the foreach binding won't re-render them.
I know this answer comes a bit late, but I thought it might be useful to others who want a more general swap solution. You can add a swap function to your observableArrays like so:
ko.observableArray.fn.swap = function(index1, index2) {
this.valueWillMutate();
var temp = this()[index1];
this()[index1] = this()[index2];
this()[index2] = temp;
this.valueHasMutated();
}
You can then use this function to swap two elements in an array given their indices:
myArray.swap(index1, index2);
For a moveUp function, you could then do something like this:
moveUp: function(category) {
var i = categories.indexOf(category);
if (i > 0) {
categories.swap(i, i+1);
}
}
I had a similar problem as I wanted jQuery drag & drop on my items.
My solution became to use knockoutjs templates to bind the beforeRemove and afterAdd events to the model. The Person Class/function is also a simple knockout view model.
In the below example I use .draggable(), but you could easily use validation. Add your own code for manipulating the observableArray and you should be good to go.
HTML:
<div data-bind="template: {foreach:attendeesToShow, beforeRemove:hideAttendee, afterAdd:showAttendee}">
<div class="person">
<img src="person.jpg" alt="" />
<div data-bind="text: firstName" ></div>
<div class="deleteimg" data-bind="click:$parent.removeAttendee" title="Remove"></div>
</div>
</div>
ViewModel:
var ViewModel = function () {
var self = this;
var at = [new Person('First', 'Person', 'first#example.com'),
Person('Second', 'Person', 'second#example.com')
];
self.attendees = ko.observableArray(at);
self.removeAttendee = function (attendee) {
self.attendees.remove(attendee);
};
this.showAttendee = function (elem) {
if (elem.nodeType === 1) {
$(elem).hide().show("slow").draggable();//Add jQuery functionality
}
};
this.hideAttendee = function (elem) {
if (elem.nodeType === 1) {
$(elem).hide(function () {
$(elem).remove();
});
}
};
};
ko.applyBindings(new ViewModel());
thanks to Michael Best for his version of moveup
my version of moveDown
moveDown: function(category) {
var array = categories();
var i = categories.indexOf(category);
if (i < arr.length) {
categories.splice(i, 2, array[i + 1], array[i]);
}
}

How can I loop through ALL DOM elements on a page?

I'm trying to loop over ALL elements on a page, so I want to check every element that exists on this page for a special class.
So, how do I say that I want to check EVERY element?
You can pass a * to getElementsByTagName() so that it will return all elements in a page:
var all = document.getElementsByTagName("*");
for (var i=0, max=all.length; i < max; i++) {
// Do something with the element here
}
Note that you could use querySelectorAll(), if it's available (IE9+, CSS in IE8), to just find elements with a particular class.
if (document.querySelectorAll)
var clsElements = document.querySelectorAll(".mySpeshalClass");
else
// loop through all elements instead
This would certainly speed up matters for modern browsers.
Browsers now support foreach on NodeList. This means you can directly loop the elements instead of writing your own for loop.
document.querySelectorAll('*').forEach(function(node) {
// Do whatever you want with the node object.
});
Performance note - Do your best to scope what you're looking for by using a specific selector. A universal selector can return lots of nodes depending on the complexity of the page. Also, consider using document.body.querySelectorAll instead of document.querySelectorAll when you don’t care about <head> children.
Was looking for same. Well, not exactly. I only wanted to list all DOM Nodes.
var currentNode,
ni = document.createNodeIterator(document.documentElement, NodeFilter.SHOW_ELEMENT);
while(currentNode = ni.nextNode()) {
console.log(currentNode.nodeName);
}
To get elements with a specific class, we can use filter function.
var currentNode,
ni = document.createNodeIterator(
document.documentElement,
NodeFilter.SHOW_ELEMENT,
function(node){
return node.classList.contains('toggleable') ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
}
);
while(currentNode = ni.nextNode()) {
console.log(currentNode.nodeName);
}
Found solution on
MDN
As always the best solution is to use recursion:
loop(document);
function loop(node){
// do some thing with the node here
var nodes = node.childNodes;
for (var i = 0; i <nodes.length; i++){
if(!nodes[i]){
continue;
}
if(nodes[i].childNodes.length > 0){
loop(nodes[i]);
}
}
}
Unlike other suggestions, this solution does not require you to create an array for all the nodes, so its more light on the memory. More importantly, it finds more results. I am not sure what those results are, but when testing on chrome it finds about 50% more nodes compared to document.getElementsByTagName("*");
Here is another example on how you can loop through a document or an element:
function getNodeList(elem){
var l=new Array(elem),c=1,ret=new Array();
//This first loop will loop until the count var is stable//
for(var r=0;r<c;r++){
//This loop will loop thru the child element list//
for(var z=0;z<l[r].childNodes.length;z++){
//Push the element to the return array.
ret.push(l[r].childNodes[z]);
if(l[r].childNodes[z].childNodes[0]){
l.push(l[r].childNodes[z]);c++;
}//IF
}//FOR
}//FOR
return ret;
}
For those who are using Jquery
$("*").each(function(i,e){console.log(i+' '+e)});
Andy E. gave a good answer.
I would add, if you feel to select all the childs in some special selector (this need happened to me recently), you can apply the method "getElementsByTagName()" on any DOM object you want.
For an example, I needed to just parse "visual" part of the web page, so I just made this
var visualDomElts = document.body.getElementsByTagName('*');
This will never take in consideration the head part.
from this link
javascript reference
<html>
<head>
<title>A Simple Page</title>
<script language="JavaScript">
<!--
function findhead1()
{
var tag, tags;
// or you can use var allElem=document.all; and loop on it
tags = "The tags in the page are:"
for(i = 0; i < document.all.length; i++)
{
tag = document.all(i).tagName;
tags = tags + "\r" + tag;
}
document.write(tags);
}
// -->
</script>
</head>
<body onload="findhead1()">
<h1>Heading One</h1>
</body>
</html>
UPDATE:EDIT
since my last answer i found better simpler solution
function search(tableEvent)
{
clearResults()
document.getElementById('loading').style.display = 'block';
var params = 'formAction=SearchStocks';
var elemArray = document.mainForm.elements;
for (var i = 0; i < elemArray.length;i++)
{
var element = elemArray[i];
var elementName= element.name;
if(elementName=='formAction')
continue;
params += '&' + elementName+'='+ encodeURIComponent(element.value);
}
params += '&tableEvent=' + tableEvent;
createXmlHttpObject();
sendRequestPost(http_request,'Controller',false,params);
prepareUpdateTableContents();//function js to handle the response out of scope for this question
}
Getting all elements using var all = document.getElementsByTagName("*"); for (var i=0, max=all.length; i < max; i++); is ok if you need to check every element but will result in checking or looping repeating elements or text.
Below is a recursion implementation that checks or loop each element of all DOM elements only once and append:
(Credits to #George Reith for his recursion answer here: Map HTML to JSON)
function mapDOMCheck(html_string, json) {
treeObject = {}
dom = new jsdom.JSDOM(html_string) // use jsdom because DOMParser does not provide client-side Window for element access
document = dom.window.document
element = document.querySelector('html')
// Recurse and loop through DOM elements only once
function treeHTML(element, object) {
var nodeList = element.childNodes;
if (nodeList != null) {
if (nodeList.length) {
object[element.nodeName] = []; // IMPT: empty [] array for parent node to push non-text recursivable elements (see below)
for (var i = 0; i < nodeList.length; i++) {
console.log("nodeName", nodeList[i].nodeName);
if (nodeList[i].nodeType == 3) { // if child node is **final base-case** text node
console.log("nodeValue", nodeList[i].nodeValue);
} else { // else
object[element.nodeName].push({}); // push {} into empty [] array where {} for recursivable elements
treeHTML(nodeList[i], object[element.nodeName][object[element.nodeName].length - 1]);
}
}
}
}
}
treeHTML(element, treeObject);
}
Use *
var allElem = document.getElementsByTagName("*");
for (var i = 0; i < allElem.length; i++) {
// Do something with all element here
}
i think this is really quick
document.querySelectorAll('body,body *').forEach(function(e) {
You can try with
document.getElementsByClassName('special_class');

Categories