how to fadein LI elements randomly? (jquery) - javascript

Hi I've got a set of <li> with a hover effect, what I want is when the page loads ALL the <li> elements fade-in randomly.
I don't want to shuffle them...they should keep their ordering intact meaning 1,2,3,4,5. I just want to make them appear on the page randomly and stay there.
Test page:
http://humayunrehman.com/hovertest/

You can do something like this:
var v = $("#blocks > li").css('visibility', 'hidden'), cur = 0;
for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
function fadeInNextLI() {
v.eq(cur++).css('visibility','visible').hide().fadeIn();
if(cur != v.length) setTimeout(fadeInNextLI, 50);
}
fadeInNextLI();
You can view a demo with your html/images here. Credit to Jordan Boesch for the sorting algorithm, the same one used in jsquares.
This will hide them all, grab at random a next :hidden one, fade it in, and 50ms later start the next one, creating a random-ish fadeIn effect. Just adjust the time as needed, also pass a time into .fadeIn() if you want. This will stop queuing effects when it's done as well.

Related

How can you dynamically slice an array in Javascript/jQuery?

I have a photo gallery that includes images that will be continuously uploaded. The PHP array has been converted/encoded to a JSON array so that I can manipulate the data with JavaScript.
Ideally, I would like to click a button ("Next Set" in the CodePen example) and load the next set (of 2) thumbnail images. This is in an effort to not load all of the images at once, which could be hundreds.
Problem: I cannot figure out how to dynamically slice the array on click (next 5 images). I can of course load, say, 2 at a time:
myArray.slice(0,2);
myArray.slice(3,5);
However, this will not work because images will be continuously added to the gallery. Furthermore, I would have to have too many sets of the above to keep slicing 5 out at a time.
I have tried:
Splitting the array into smaller arrays
for loops and $.each loops
I essentially need to be able to move the start and end index of the slice by (for example) 2 on click. Right now it just keeps slicing the same two images because the slicing is not dynamic.
Here is my CodePen
I don't think there's a way to do exactly what you want, but you can just keep track of where you were in the array and do a slice from there, like this:
var nextSet = myArray.slice(lastIndex, lastIndex + 2);
Replace your existing click() with this (including the declaration of lastIndex) to try it:
var lastIndex = 0
$('.button').click(function() {
var nextSet = myArray.slice(lastIndex, lastIndex + 2);
lastIndex += 2;
for (var i = 0; i < 2; i++) {
var li = $('<li/>').attr('role', 'menuitem').appendTo('.myList').append('<img src=' + nextSet[i] + '>');
}
});
Note that I've moved the slice() line outside the for loop. There's no need to slice a new array for every iteration.
Here's a CodePen using .slice().
An alternate method is to use to shift() to peel off the first item in the array with each iteration:
var nextItem = myArray.shift()
This is destructive though (it removes the item from the original array), so you'll need to make a copy of the original array first if you want to use it for anything else. Replace your click() with:
$('.button').click(function() {
for (var i = 0; i < 2; i++) {
var nextItem = myArray.shift();
var li = $('<li/>').attr('role', 'menuitem').appendTo('.myList').append('<img src=' + nextItem + '>');
}
});
Here's a CodePen using .shift().
your problem is simple i think. you do a slice and allways get back the same array
var array = [0,1,2,3,4,5];
let newArray1 = array.slice(0,2); // returns a new array
let newArray2 = array.slice(0,2); // returns the same new array
for(var i = 0; i < 2; i = i+2) {
result = array.slice(i, i+2);
console.log(result);
}

How to wrap elements based on loop, plus amount of modulus?

I need to wrap every third instance of a <div> in some HTML dynamically, and, if there is a remainder, to wrap that less-than-three amount in a similar manner, so it would serve as the last instance of the "wrap".
Getting every third instance wrapped is pretty basic:
var divs = $(".someclass");
var limit = 10;
for(var i = 0; i < limit; i+=3) {
divs.slice(i, i+3).wrapAll("<div class='classwrap'></div>");
}
However, because there is a remainder of 1 in this example, and I am otherwise dynamically generating HTML elsewhere (too complex to demo here, but that aspect works fine), the result in this example creates four .classwrap divs wrapping sets of three .someclass divs, giving me twelve .someclass divs, but not ten, however.
What I'm trying to achieve in this example is indeed four sets of .classwrap divs, but with the first three of those wrapper sets each containing three .someclass divs, and then getting a fourth .classwrap div that contains only one .someclass div, for the grand total of ten .someclass divs, as indicated by the limit variable.
I have tried to sneak in a modulus operator somewhere in my loop but it always throws off the math and wrapping accordingly.
Here is the answer I think you are looking for.
You need to determine when the last grouping is being made.
then use the modo value to only wrap that many sections.
Updated fiddle
var divs = $(".someclass");
var limit = 10;//divs.length;
var grouper = 3
var modo = limit % grouper;
for(var i = 0; i < limit; i+=grouper) {
var offset = grouper;
if(modo + i === limit) {
offset = modo;
}
divs.slice(i, i+offset).wrapAll("<div class='classwrap' style='background-color:#def;'></div>");
}
OR
replace your initial selection with:
Fiddle for slice
var limit = 10;
var divs = $(".someclass").slice(0,limit);

Non repeating array number (which is added twice or more with Jquery

I know the question about obtaining a random number with javascript (non repeating) is often asked but in my case I append the same jquery code twice or three time and I would like to obtain different information each time.
First i have a large array (150 items) which is built this way :
var arr = [
{
"Numéro": "1",
"Chinois": "爱",
"Pinyin": "ài",
"Français": "aimer, affection, apprécier",
"Classificateurs": ""
},
Then I found on another post this random function :
while(arr.length < 150){
var randomnumber=Math.ceil(Math.random()*147)
var found=false;
for(var i=0;i<arr.length;i++){
if(arr[i]==randomnumber){found=true;break}
}
if(!found)arr[arr.length]=randomnumber;
}
Then I append the array information (I tried randomly - It's a flashcard kind of page so on click, the next "index" should be randomized and unique) on the page :
$('#qcm-az, .suivantQcm1').on ('click', function(qcmaz){
$('#reponse1').html(arr[index].Français);
$('#reponse2').html(arr[147 -Math.floor((Math.random() * 23)+1)].Français);
$('#reponse3').html(arr[99 - Math.floor((Math.random() * 65)+1)].Français);
$('#reponse4').html(arr[43 - Math.floor((Math.random() * 21)+1)].Français);
index = randomnumber;
});
So basically on page load or (if the next arrow is clicked) I would like the "index = randomnumber" to be ran once again but it seems stuck (because the random number seems allocated once and for all).
Finally you can see that, on my different divs, I'm using a not so random function to get a different index number. I often encounter a problem which is that the "good answer" (reponse1) is the same as in one of the "wrong answer" (reponse2,3 or 4).
I hope I explained myself clearly - I'm beginning in Javascript/Jquery. Thank you in advance.
Edit : I added a fiddle to show you the problem (just click on the body to move to next item - which is stuck after one click here)
http://jsfiddle.net/Hv8SD/
You array-shuffling algorithm is fully incorrect.
A can propose this variant:
var counter = 0, newArray = [];
while(counter < 147)
{
var randomnumber=Math.ceil(Math.random()*147 - 1)
if(!newArray[randomnumber]) // if newArray doesn't contains index `randomnumber`
{
newArray[randomnumber]=arr[counter];
counter++;
};
};
JSFiddle DEMO

Implementing shuffle images function

Im looking for some advice on how to start a shuffle image function, so I have 6 images atm in a div box and I want a function that allows them to shuffle around, how should I start?? Should I put the images in a separate div as well? any help or example code appreciated, thanks
Following is a jQuery solution. You can achieve same results using vanilla JavaScript but it will require few extra lines of code.
<div id="deck">
<div><img src="" /></div>
<div><img src="" /></div>
.
.
.
</div>
// Fisher–Yates Shuffle (Knuth variant)
// To shuffle an array a of n elements (indices 0..n-1):
// for i from n - 1 downto 1 do
// j <- random integer with 0 <= j <= i
// exchange a[j] and a[i]
// jQuery specific:
// 1) remove elements from DOM and convert them into a native JavaScript array
// 2) apply algorithm
// 3) inject the array back to DOM
var a = $("#deck > div").remove().toArray();
for (var i = a.length - 1; i >= 1; i--) {
var j = Math.floor(Math.random() * (i + 1));
var bi = a[i];
var bj = a[j];
a[i] = bj;
a[j] = bi;
}
$("#deck").append(a);
Demo here
I've implemented something like this for a memory card game, so you can probably get some hints from that. Just do a resources search for 'shuffle' in my .js files and you should get an idea how I've done it. From memory, I originally put all my images in a div, then move them around with the shuffle function. I think later on I started shuffling an array of URLs instead then generating the image elements later.
I used Ca-Phun Ung's 'Shuffle' JQuery plugin (although I think I re-wrote my own version to better understand its inner workings). You may find some useful information with that as well. See JQuery Shuffle
Ok, I got this!
var divs = $('selector to get all divs'); // This could be $('img');
function shuffle(divs, iterations) {
var size = divs.size();
for(var i = iterations; i > 0; i--) {
// Pick two divs at random
var div1 = divs[Math.floor(Math.random() * size)],
div2 = divs[Math.floor(Math.random() * size)];
// Ensure they are different divs
if(div1.is(div2)) {
continue;
}
// Swap the two divs
div1.clone().insertAfter(div2);
div2.detach().insertAfter(div1);
div1.detach();
}
};
shuffle(divs, 1000);
Although this will probably be better if you put a divs.hide(), then divs.show() so that you don't see the thrashing. However, maybe that is what you want? May you want a delay in there and use jQuery's animate function to make it fancy. This particular solution requires that the img's position in the DOM determines the location. A more complex solution would be to swap the css position during the loop.
var savedLeft = div1.css("left"),
savedTop = div1.css("top");
div1.css("left", div2.css("left"));
div1.css("top", div2.css("top"));
div2.css("left", savedLeft);
div2.css("top", savedTop);
I haven't actually TRIED this yet, but it looks right from here :P

Where to put this block of script so that this slideshow can move automatically?

I asked a question before on how to make the jQuery Blinds slideshow move automatically and somebody answered on this page (the one with 12 votes):
Is there a way to make this slideshow move automatically?
Seems like the code is working for most people but I can't get it to work for me. I used the original demo file and placed the code at the very bottom of jquery.blinds-0.9.js, right after "})(jQuery);" but still the slideshow isn't moving. What am I doing wrong? I checked the class names and they are correct.
This is that block of script:
var SlideChanger = function(seconds_each) {
var index = -1;
// on the first cycle, index will be set to zero below
var maxindex = ($(".change_link").length) - 1;
// how many total slides are there (count the slide buttons)
var timer = function() {
// this is the function returned by SlideChanger
var logic = function() {
// this is an inner function which uses the
// enclosed values (index and maxindex) to cycle through the slides
if (index == maxindex)
index = 0; // reset to first slide
else
index++; // goto next slide, set index to zero on first cycle
$('.slideshow').blinds_change(index); // this is what changes the slide
setTimeout(logic, 1000 * seconds_each);
// schedule ourself to run in the future
}
logic(); // get the ball rolling
}
return timer; // give caller the function
}
SlideChanger(5)(); // get the function at five seconds per slide and run it
Try wrapping the last line SlideChanger(5)(); in a document.ready, like this:
$(function(){SlideChanger(5)();})
Otherwise $(".change_link").length will prob return 0

Categories

Resources