I have a page where I output the following
This is the html in my template
<ul id="process"><span>Process: </span>
This is my minified Javascript (functions.js)
$(window).load(function () {
var a = $("#slider").children("img");
currentIndex = 0;
slideCount = a.length;
fadeDuration = 1E3;
navigation = $("#process");
navCnt = 0;
navNumFix = 1;
for (i = 0; i < slideCount; i++) navigation.append('<li>' + navNumFix+++"</li> ");
$(".navItem").click(function () {
var b = $(this).attr("data"),
c = currentIndex;
currentIndex = b;
c != currentIndex && ($(a[c]).fadeOut(fadeDuration), $(a[currentIndex]).fadeIn(fadeDuration))
})
});
For my slider this all outputs the ul tag and attaches the list item via Javascript as follows:
<ul id="process"><span>Process: </span>
<li>1</li>
<li>2</li>
</ul>
Instead of outputting the ul tag in my template, how can I output the ul tag only when the script calls for it? Kind of like the list item above.
This should do... putting your template in display none at first, then showing it after adding your list elements :
<ul style="display:none" id="process"><span>Process: </span></ul>
Javascript :
$(window).load(function () {
var a = $("#slider").children("img");
currentIndex = 0;
slideCount = a.length;
fadeDuration = 1E3;
navigation = $("#process");
navCnt = 0;
navNumFix = 1;
for (i = 0; i < slideCount; i++) navigation.append('<li>' + navNumFix+++"</li> ");
$(".navItem").click(function () {
var b = $(this).attr("data"),
c = currentIndex;
currentIndex = b;
c != currentIndex && ($(a[c]).fadeOut(fadeDuration), $(a[currentIndex]).fadeIn(fadeDuration))
})
// Display the ul if there are slides
if(slideCount > 0)
navigation.show();
});
EDIT : Added the condition to show the ul only when there are slides
Related
I have a gallery with images, these images can be dragged to another place and also dragged back. When dragging them back, a sort function places them at the correct place again (order of ID).
now since I made this function, my onClick Tag function for the Image tag doesn't work anymore
can someone explain me why this is and how I can solve this?
HTML (Razor):
<ul class="gallery col-md-8 borderBoxes" id="gallery">
#for (int i = 0; i < Model.PageList.Count; i++)
{
<li class="imageListItem ui-icon-zoomin" id="#Model.PageList[i].ID">
<figure id="#(i+1)">
<img class="pages small" src="data:image/jpeg;base64,#Model.PageList[i].ImageBaase64" onclick="imageLarger(this)" />
</figure>
</li>
}
</ul>
OnClickFunction (JS):
function imageLarger(image) {
if ($(image).width() === 700) {
$(image).width(100);
setTimeout(function () {
$(image).removeClass("largePages");
$("li", $("#gallery")).draggable("option", "disabled", false);
}, 300);
} else {
$("li", $("#gallery")).draggable("option", "disabled", true);
$(image).width(700);
$(image).addClass("largePages");
}
};
SortFunction (JS):
function sortByImageID() {
var gallery = document.getElementById("gallery");
var galleryItems = gallery.getElementsByClassName("imageListItem");
for (var i = 0; i < galleryItems.length; i++) {
var listitems = [];
for (i = 0; i < galleryItems.length; i++) {
listitems.push(galleryItems.item(i));
}
listitems.sort(function (a, b) {
var compA = a.getElementsByTagName("figure")[0].getAttribute('id');
var compB = b.getElementsByTagName("figure")[0].getAttribute('id');
return (parseInt(compA) < parseInt(compB)) ? -1 : (parseInt(compA) > parseInt(compB)) ? 1 : 0;
});
for (i = 0; i < listitems.length; i++) {
gallery.appendChild(listitems[i]);
}
}
}
The code below is for listing blogger posts within a Label Name, if the post has the specific Label Name it will be shown in this list. I would like to be able to change the appearance of how everything is displayed by changing where the post image would look, and where the title would look, change background color, add borders, shadows change the font etc ...(I know how to change the appearance with css, but I do not know how to integrate the code below with css and html) At the moment the code shows the title and the right of the title the image.
var startIndex = 1;
var maxResults = 5;
var allResults = [];
function sendQuery12()
{
var scpt = document.createElement("script");
scpt.src = "https://levon-ltr.blogspot.com//feeds/posts/summary?alt=json&callback=processPostList12&start-index=" + startIndex + "&max-results=" + maxResults;
document.body.appendChild(scpt);
}
function printArrayResults(root)
{
//Sort Alphebetically
allResults.sort(function(a, b){
var a_string = a.children[0].textContent ;
var b_string = b.children[0].textContent ;
if(a_string < b_string) return -1;
if(a_string > b_string) return 1;
return 0;
})
var elmt = document.getElementById("postList12");
for (index = 0; index < allResults.length; index++) {
elmt.appendChild(allResults[index]);
}
}
function processPostList12(root)
{
var elmt = document.getElementById("postList12");
if (!elmt)
return;
var feed = root.feed;
if (feed.entry.length > 0)
{
for (var i = 0; i < feed.entry.length; i++)
{
var entry = feed.entry[i];
var title = entry.title.$t;
var date = entry.published.$t;
if( entry.media$thumbnail != undefined ){
var imageThumb = entry.media$thumbnail.url ;
} else {
var imageThumb = 'https://i.imgur.com/PqPqZQN.jpg' ;
}
for (var j = 0; j < entry.link.length; j++)
{
if (entry.link[j].rel == "alternate")
{
var url = entry.link[j].href;
if (url && url.length > 0 && title && title.length > 0)
{
var liE = document.createElement("li");
var a1E = document.createElement("a");
var postImage = document.createElement("img");
a1E.href = url;
a1E.textContent = title;
postImage.src = imageThumb;
liE.appendChild(a1E);
liE.appendChild(postImage);
//elmt.appendChild(liE);
allResults.push(liE);
}
break;
}
}
}
if (feed.entry.length >= maxResults)
{
startIndex += maxResults;
sendQuery12();
} else {
printArrayResults();
}
}
}
sendQuery12();
<div>
<ul id="postList12"></ul>
</div>
This creates stuff you can style with CSS. For example:
#postList12 li {
border: 1px solid blue;
}
Use the inspector in your browser to see what it makes. If you want to change the order of elements or add new ones you’ll have to edit the script to do that.
success: function(f) {
var thumbnailbox = $("#warpper");
for (var obj in f) {
foldersrcname = [];
//put all folder name to array
foldersrcname.push(f[obj].name);
for (var c = 0; c < foldersrcname.length; c++) {
var temp = "";
temp += < li class = "image_icon" > < /li>
}
}
thumbnailbox.html(temp);
var lis = $('#warpper ul li');
var i = 0;
lis.each(function() {
i++;
});
var total = lis.length;
//i need to get last element is been added//
if (i === total) {
//remove something
}
}
i had a ajax which will return image src with loop , it will create li and add into #warpper , my question will be how i gonna know the last image src have been added ?
so lets said the return ajax of the foldersrcnname.length is 7 , and the loop is going to continue adding the src into li one by one, how i check when will be the last loop ?
i need to know when the loop finish added the last one so i can remove something.
for (var c = 0; c < foldersrcname.length; c++) {
var temp = "";
if((c+1==foldersrcname.length){
temp += < li class = "image_icon last-li">< /li>
}
temp += < li class = "image_icon" > < /li>
}
And you can get last li using
$('#warpper ul li.last-li')
EDIT :
$('#warpper ul li.last-li').length
I have a TODO list app with an Unordered list. Within it I have a few list items. The li classes are high,medium,low. I would like li's with the class high to be placed before li's with the class medium and last ones with low.
<ul id="tasks">
<li id="item3" class="priority low"><span></span><span>This is a low priority task</span></li>
<li id="item4" class="priority high"><></span><span>This is a high priority task</span></li>
<li id="item5" class="priority low"><span></span><span>This is another Low</span></li>
<li id="item7" class="priority medium"><span></span><span>And now a Medium</span></li>
</ul>
So the li with id of item4 should be first and then it should be item7 and then the li's with class low after.
Here's a pure JS version of #ŠimeVidas jQuery solution.
var tasks = document.querySelector('#tasks'),
items = document.querySelectorAll('#tasks > li');
for (var i = 0, arr = ['high', 'medium', 'low']; i < arr.length; i++) {
for (var j = 0; j < items.length; j++) {
if (~(" " + items[j].className + " ").indexOf(" " + arr[i] + " "))
tasks.appendChild(items[j]);
}
}
Assuming you can use jQuery, and assuming your list is not very big, and assuming you've only got these three fixed types with no plans on changing this, I'd probably just dump the whole set into memory, clear out the list, then put them back in the list in order. Something like:
jQuery(document).ready(function() {
var i;
var items = jQuery("#tasks li");
var lowItems = [];
var medItems = [];
var highItems = [];
for (i = 0; i < items.length; ++i) {
var jqItem = jQuery(items[i]);
if (jqItem.hasClass("low")) lowItems.push(jqItem);
if (jqItem.hasClass("medium")) medItems.push(jqItem);
if (jqItem.hasClass("high")) highItems.push(jqItem);
}
var tasks = jQuery("#tasks");
tasks.html("");
for (i = 0; i < highItems.length; ++i) {
tasks.append(highItems[i]);
}
for (i = 0; i < medItems.length; ++i) {
tasks.append(medItems[i]);
}
for (i = 0; i < lowItems.length; ++i) {
tasks.append(lowItems[i]);
}
});
Try this:
$(function(){
var sorter = [],
tasks = $('#tasks');
$('li.priority').each(function(){
var $this = $(this),
priority = $this.hasClass('high') ? 3 : ($this.hasClass('medium') ? 2 : 1);
sorter.push({
el : this,
priority : priority
});
}).detach();
sorter.sort(function(a, b){
return a.priority - b.priority;
});
$.each(sorter, function(){
tasks.append(this.el);
});
});
With no jquery:
<ul id="tasks">
<li id="item3" class="priority low"><span></span><span>This is a low priority task</span></li>
<li id="item4" class="priority high"><></span><span>This is a high priority task</span></li>
<li id="item5" class="priority low"><span></span><span>This is another Low</span></li>
<li id="item7" class="priority medium"><span></span><span>And now a Medium</span></li>
</ul>
<script type="text/javascript">
var tasks = document.getElementById("tasks");
var liElements = tasks.getElementsByTagName("li");
var lowPriority = [];
var mediumPriority = [];
var highPriority = [];
var removal = [];
for (var i = 0, len = liElements.length; i < len; i++) {
if (liElements[i].getAttribute("class").indexOf("low") > -1) lowPriority.push(liElements[i].cloneNode(true));
if (liElements[i].getAttribute("class").indexOf("medium") > -1) mediumPriority.push(liElements[i].cloneNode(true));
if (liElements[i].getAttribute("class").indexOf("high") > -1) highPriority.push(liElements[i].cloneNode(true));
removal.push(liElements[i]);
}
for (var i = 0, len = removal.length; i < len; i++ ) {
var liItem = removal[i];
liItem.parentNode.removeChild(liItem);
}
for( var i = 0, len = lowPriority.length; i < len; i++){
tasks.appendChild(lowPriority[i]);
}
for (var i = 0, len = mediumPriority.length; i < len; i++) {
tasks.appendChild(mediumPriority[i]);
}
for (var i = 0, len = highPriority.length; i < len; i++) {
tasks.appendChild(highPriority[i]);
}
</script>
Here's another jQuery–less option:
// Just a helper
function toArray(obj) {
var result = [];
for (var i=0, iLen=obj.length; i<iLen; i++) {
result[i] = obj[i];
}
return result;
}
// Uses querySelectorAll, but could use getElementsByTagName instead
function sortByPriority(id) {
var nodes;
var el = document.getElementById(id);
if (el) {
nodes = toArray(el.querySelectorAll('li.priority'));
nodes.sort(function(a, b) {
function getIndex(el) {
return el.className.indexOf('low') != -1? 1 :
el.className.indexOf('medium') != -1? 2 :
el.className.indexOf('high') != -1? 3 :
0; // default
}
return getIndex(b) - getIndex(a);
});
for (var i=0, iLen=nodes.length; i<iLen; i++) {
el.appendChild(nodes[i]);
}
}
}
It uses a few more lines that a jQuery (or perhaps any library) based solution but you don't have to load several thousand lines of library either.
Also, this runs about 5 times faster in Firefox and IE 9 and 10 times faster in Chrome than a jQuery solution (see http://jsperf.com/sortelementlist).
With pure JavaScript, and simple code!
var tasks = document.getElementById("tasks");
var lis = tasks.getElementsByTagName("li");
var lisarr = Array.prototype.slice.call(lis);
var priority = function(e){
var prio = {low: 0, medium: 1, high: 2};
return prio[e.getAttribute("class").match(/low|high|medium/)[0]];
};
lisarr.sort(function(a,b){
var ap = priority(a), bp = priority(b);
return bp - ap;
});
tasks.innerHTML = lisarr.reduce(function(prev, current){
return prev + current.outerHTML;
}, '');
I have a list:
<ul>
<li>milk</li>
<li>butter</li>
<li>eggs</li>
<li>orange juice</li>
<li>bananas</li>
</ul>
Using javascript how can I reorder the list items randomly?
var ul = document.querySelector('ul');
for (var i = ul.children.length; i >= 0; i--) {
ul.appendChild(ul.children[Math.random() * i | 0]);
}
This is based on Fisher–Yates shuffle, and exploits the fact that when you append a node, it's moved from its old place.
Performance is within 10% of shuffling a detached copy even on huge lists (100 000 elements).
http://jsfiddle.net/qEM8B/
Simply put, like this:
JS:
var list = document.getElementById("something"),
button = document.getElementById("shuffle");
function shuffle(items)
{
var cached = items.slice(0), temp, i = cached.length, rand;
while(--i)
{
rand = Math.floor(i * Math.random());
temp = cached[rand];
cached[rand] = cached[i];
cached[i] = temp;
}
return cached;
}
function shuffleNodes()
{
var nodes = list.children, i = 0;
nodes = Array.prototype.slice.call(nodes);
nodes = shuffle(nodes);
while(i < nodes.length)
{
list.appendChild(nodes[i]);
++i;
}
}
button.onclick = shuffleNodes;
HTML:
<ul id="something">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<button id="shuffle" type="button">Shuffle List Items</button>
Demo: http://jsbin.com/itesir/edit#preview
var list = document.getElementById("something");
function shuffleNodes() {
var nodes = list.children, i = 0;
nodes = Array.prototype.sort.call(nodes);
while(i < nodes.length) {
list.appendChild(nodes[i]);
++i;
}
}
shuffleNodes();
Use this:
function htmlShuffle(elem) {
function shuffle(arr) {
var len = arr.length;
var d = len;
var array = [];
var k, i;
for (i = 0; i < d; i++) {
k = Math.floor(Math.random() * len);
array.push(arr[k]);
arr.splice(k, 1);
len = arr.length;
}
for (i = 0; i < d; i++) {
arr[i] = array[i];
}
return arr;
}
var el = document.querySelectorAll(elem + " *");
document.querySelector(elem).innerHTML = "";
let pos = [];
for (let i = 0; i < el.length; i++) {
pos.push(i);
}
pos = shuffle(pos);
for (let i = 0; i < pos.length; i++) {
document.querySelector(elem).appendChild(el[pos[i]]);
}
}
htmlShuffle("ul");
<ul>
<li>milk</li>
<li>butter</li>
<li>eggs</li>
<li>orange juice</li>
<li>bananas</li>
</ul>
Here is a very simple way to shuffle with JS:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random()});
http://www.w3schools.com/js/js_array_sort.asp
I was searching for a prototype function. Maybe this helps someone.
Element.prototype.shuffleChildren = function() {
for (var i = this.children.length; i >= 0; i--) {
this.appendChild(this.children[Math.random() * i | 0]);
}
};
document.querySelector('body').shuffleChildren();
Here's a solution that does not use a loop.
function shuffle_children(element) {
element.append(...Array.from(element.children).sort(function () {
return Math.random() - 0.5;
}));
}
Based no #Alexey Lebedev's answer, if you prefer a jQuery function that shuffles elements, you can use this one:
$.fn.randomize = function(selector){
var $elems = selector ? $(this).find(selector) : $(this).children();
for (var i = $elems.length; i >= 0; i--) {
$(this).append($elems[Math.random() * i | 0]);
}
return this;
}
And then call it like this:
$("ul").randomize(); //shuffle all the ul children
$("ul").randomize(".item"); //shuffle all the .item elements inside the ul
$(".my-list").randomize(".my-element"); //shuffle all the .my-element elements inside the .my-list element.