I have a method like so:
function randomHighlights() {
loops++;
var newRandom = Math.floor(Math.random() * 12 + 1);
while (lastRandom == newRandom) {
newRandom = Math.floor(Math.random() * 12 + 1);
}
lastRandom = newRandom;
var li = $('#u-' + newRandom);
$('#home-grid-list li').random().addClass(function() {
var liClass = $(this).attr('class').split(/\s+/);;
$('#home-grid-list li').removeClass('color-off');
$('#home-grid-list li.' + liClass[0]).addClass('color-off');
clearTimeout(timer);
});
$('#home-grid-list li').removeClass('text-on');
timer = setTimeout(randomHighlights, 2500);
if (loops == 20) {
clearTimeout(timer);
longHighlight();
}
}
It highlights 4 images at a time. The problem is I don't want it to be random anymore because there are only 3 different choices for it to be random and obviously it ends up picking the same block more than once creating a lag effect. Now I want to cycle through the #home-grid-list and highlight them cyclically. Any advice on how to do that?
longHighlight() just highlights a random block of 4 pictures for longer than returns to this method.
EDIT: Is this more what you had in mind?
JS:
var items = $('#home-grid-list').children('li');
var len = items.length;
var arr = [0,1,2,3];
window.setInterval(cycle,1000);
function cycle() {
items.removeClass('highlight');
for (var i=0; i<4; i++) {
var temp = arr.shift();
arr.push(((temp+4<len)?temp+4:temp+4-len));
}
for (var i=0; i<4; i++) {
items.filter('#u-'+arr[i]).addClass('highlight');
}
}
Here's an updated fiddle.
Something like this?
JS:
var items = $('#home-grid-list').children('li');
var len = items.length;
var arr = [0,1,2,3];
window.setInterval(cycle,1000);
function cycle() {
items.removeClass('highlight');
var temp = arr.shift();
arr.push(((temp+4<len)?temp+4:temp+4-len));
console.log(arr);
for (var i=0; i<4; i++) {
items.eq(arr[i]).addClass('highlight');
}
}
Here's a fiddle.
Related
This question already has an answer here:
How to create a typewriter effect in JavaScript THAT will take into account html tag rules?
(1 answer)
Closed 1 year ago.
I understand there are other ways to create a typing effect but I can't seem to figure out the logic of using nested for loop.
var changingtext = document.querySelector(".text");
var arr = ["hard","Fun","a Journey","Career", "Countless hours"];
var length;
var index = 0;
var count=0;
var letter = "";
let currentText = "";
window.addEventListener("DOMContentLoaded", function(){
type();
});
function type(){
setTimeout(function(){
for(var i=0; i<arr.length; i++){
length = arr[i].length;
for(j=0; j<length;j++){
letter += arr[i].charAt(j);
changingtext.textContent = letter;
console.log(letter);
}
}
}, 200);
}
You should just schedule the timeouts in a single loop, incrementing how long to wait:
var changingtext = document.querySelector(".text");
var arr = ["hard","Fun","a Journey","Career", "Countless hours"];
var length;
var index = 0;
var count=0;
var letter = "";
let currentText = "";
window.addEventListener("DOMContentLoaded", function(){
type();
});
function type(){
let timeout = 200;
for(var i=0; i<arr.length; i++){
length = arr[i].length;
letter += ' ';
for(j=0; j<length * 2;j++){
if (j > length - 1) {
letter = letter.slice(0, -1)
} else {
letter += arr[i].charAt(j);
}
timeout += 200;
((timeout, letter) => {
setTimeout(() => {
changingtext.textContent = letter;
console.log(letter);
}, timeout);
})(timeout, letter);
}
}
}
<div class="text"/>
Or maybe you mean like this?
var changingtext = document.querySelector(".text");
var arr = ["hard","Fun","a Journey","Career", "Countless hours"];
var length;
var index = 0;
var count=0;
var letter = "";
let currentText = "";
window.addEventListener("DOMContentLoaded", function(){
type();
});
function type(){
let timeout = 200;
for(var i=0; i<arr.length; i++){
length = arr[i].length;
letter = '';
for(j=0; j<length * 2;j++){
if (j > length - 1) {
letter = letter.slice(0, -1)
} else {
letter += arr[i].charAt(j);
}
timeout += 200;
((timeout, letter, restart) => {
setTimeout(() => {
changingtext.textContent = letter;
console.log(letter);
if (restart) type();
}, timeout);
})(timeout, letter, i === arr.length - 1 && j === (length * 2) - 1);
}
}
}
<div class="text"/>
I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});
So I'm trying to find how many of each number from zero to ten is generated in a random array.
I created a random array list
i=0;
var ranList=[];
while (i<20){
i++;
ranList.push(Math.floor(10*Math.random()));
}
//count each number
document.write(ranList.sort().join("<br>"));
/*Then I made a function to count /elements from this array
*/
function ctnumber(array,elem){
var ct=0;
var j =0;
while(j<array.length)
{
j++;
if(array[j]==elem){
ct+=1;}
}
}
return ct;
}
alert(ctnumber(ranList,5));
The second function doesn't execute, any idea why?
Thank you!
First you should avoid using the name array for you variable:
http://www.w3schools.com/js/js_reserved.asp
Your brackets are also wrong. Change your function to this and it should work:
function ctnumber(arr,elem){
var ct=0;
var j =0;
while(j<arr.length)
{
j++;
if(arr[j]==elem){
ct+=1;}
}
return ct;
}
The problem with your code, as stated by Pardeep in his comment, is that you have an extra } after your ct+=1; in your second while loop.
The correct code would be: Fiddle
i = 0;
var ranList = [];
while (i < 20) {
i++;
ranList.push(Math.floor(10 * Math.random()));
}
//count each number
document.write(ranList.sort().join("<br>"));
function ctnumber(array, elem) {
var ct = 0;
var j = 0;
while (j < array.length) {
j++;
if (array[j] == elem) {
ct += 1; // NOTE NO } HERE NOW
}
}
return ct;
}
alert(ctnumber(ranList, 5));
I also suggest a bit of a code cleanup:
var i = 0;
var ranList = [];
while (i < 20) {
i++;
ranList.push(Math.floor(10 * Math.random());
}
function countNumbers(list, elem) {
var count = 0;
// For loops are generally more readable for looping through existing lists
for (var i = 0; i < list.length; i++) {
if (list[i] == elem) {
count++;
}
}
return count;
}
alert(countNumber(ranList, 5));
Please note that console.log() is a much better debugging tool, it can be accessed by F12 in Firefox and Chrome/IE.
I can not figure out why this is not working, should be returning an array with four distinct values, but it doesn't
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
while ($.inArray(randomNumbers[i], randomNumbers) !== -1) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
}
}
for (var i = 0; i < randomNumbers.length; i++) {
if ($('#output').html() !== '') {
var existingOutput = $('#output').html();
$('#output').html(existingOutput + randomNumbers[i]);
} else {
$('#output').html(randomNumbers[i]);
}
}
});
Can cut out the if and the second loop by appending the joined array
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
var ran =newNum();
/* unique check*/
while ( $.inArray( ran, randomNumbers) >-1){
ran=newNum();
}
randomNumbers.push(ran)
}
$('#output').append( randomNumbers.join(''))
});
function newNum(){
return Math.floor((Math.random() * 9) + 1);
}
Alternate solution using a shuffle method ( found in this post ):
var a=[1,2,3,4,5,6,7,8,9];
function Shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
$('#output').append( Shuffle(a).splice(0,4).join(''))
If you generate a number and put it in the array, don't you think that $.inArray() will tell you so?
Your while loop is guaranteed to hang. A member of the array (randomNumbers[i]) is always, of course, going to be in the array. In fact $.inArray() when called to see if randomNumbers[i] is in the array will return i (if it's nowhere else, which in this case it can't be). Your loop won't get past the first number, so it'll just be 0.
I don't understand the point of your while loop. inArray only returns -1 if the value isn't found, which it will always be found, so you're just creating an infinite loop for yourself that will keep resetting the random number generated.
If you're just trying to add four random numbers to a div, this worked for me:
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
}
for (var i = 0; i < randomNumbers.length; i++) {
if ($('#output').html() !== '') {
var existingOutput = $('#output').html();
$('#output').html(existingOutput + randomNumbers[i]);
} else {
$('#output').html(randomNumbers[i]);
}
}
});
Further refactored:
$(document).ready(function (e) {
var randomNumbers = new Array();
for (var i = 0; i < 4; i++) {
randomNumbers[i] = Math.floor((Math.random() * 9) + 1);
}
for (var i = 0; i < randomNumbers.length; i++) {
$('#output').append(randomNumbers[i]);
}
});
I'm trying to create a simple memory matching game and I'm having trouble assigning one number to each table cell from my cardValues array. My giveCellValue function is supposed to generate a random number then pick that number from the array and give it to one of the table cells but I'm a little over my head on this one and having trouble accomplishing this task.
var countCells;
var cardValues = [];
var checker = true;
var createTable = function (col, row) {
$('table').empty();
for (i = 1; i <= col; i++) {
$('table').append($('<tr>'));
}
for (j = 1; j <= row; j++) {
$('tr').append($('<td>'));
}
countCells = row * col;
};
createTable(3, 6);
for (i = 1; i <= countCells / 2; i++) {
cardValues.push(i);
if (i === countCells / 2 && checker) {
checker = false;
i = 0;
}
}
var giveCellValue = function () {
var random = Math.ceil(Math.random() * cardValues.length) - 1;
for (i = 0; i <= cardValues.length; i++) {
$('td').append(cardValues[random]);
cardValues.splice(random, 1);
}
};
giveCellValue();
console.log(cardValues);
Use
var countCells;
var cardValues = [];
var checker = true;
var createTable = function (col, row) {
$('table').empty();
for (var i = 0; i < col; i++) {
$('table').append($('<tr>'));
}
for (var j = 0; j < row; j++) {
$('tr').append($('<td>'));
}
countCells = row * col;
};
createTable(3, 6);
for (i = 0; i < countCells; i++) {
cardValues.push(i % 9 + 1);
}
var giveCellValue = function () {
var len = cardValues.length, tds = $('td');
for (var i = 0; i < len; i++) {
var random = Math.floor(Math.random() * cardValues.length);
tds.eq(i).append(cardValues.splice(random, 1));
}
};
giveCellValue();
console.log(cardValues);
Demo: Fiddle
Leaving aside the problems that have already been mentioned in the comments above...
If I understand it right, you want to assign each of the numbers in cardValues to a random table cell?
Seems like the problem is with this line:
var random = Math.ceil(Math.random() * cardValues.length) - 1;
What this does is generates a random number once. If you access the variable random at a later time, you're not calling the full line of code again, you're just getting the same value that was calculated the first time. E.g. if the above code runs, spits out '7' as its random number and stores that in random, then every time you go through the for loop, the value of random will always be '7' rather than being re-generated every time - make sense?
Try putting the randomiser inside the for loop - that way it will be run multiple times, generating a new random number every time:
var giveCellValue = function () {
var random;
for (i = 0; i <= cardValues.length; i++) {
random = Math.ceil(Math.random() * cardValues.length) - 1;
$('td').append(cardValues[random]);
cardValues.splice(random, 1);
}
};
Actually, I'd change line 4 above to random = Math.floor(Math.random() * cardValues.length); too which should have the same effect.