Getting loop to work in my script - javascript

I basically want this loop to produce random spaces in a grid I am developing, but cannot get it to work in my script.
I have the correct loop I just can't get it to work with the rest of my script
I have just edited and it still doesn't work, any other ideas?
var listOfWords = {};
var ul = document.getElementById("wordlist");
var i;
for(i = 0; i < ul.children.length; ++i){
listOfWords[ul.children[i].getAttribute("data-word")] = {
"pic" : ul.children[i].getAttribute("data-pic"),
"audio" : ul.children[i].getAttribute("data-audio")
};
}
console.log(listOfWords);
var chosenWords = new Array();
for(var x = 0; x < 6; x++)
{
var rand = Math.floor(Math.random() * (listOfWords.length+1));
chosenWords.push(listOfWords[rand]);
if (chosenWords.length < 12){
chosenWords.push(' ');
}
}
var shuffledWords = Object.keys(listOfWords).slice(0).sort(function() {
return 0.5 - Math.random();
}).slice(0, 6);
var guesses = {};
console.log(shuffledWords);
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < Object.keys(shuffledWords).length - 1; i += wordsPerRow) {
var row = document.createElement('tr');
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
guesses[word] = [];
for (var k = 0; k < word.length; ++k) {
var cell = document.createElement('td');
$(cell).addClass('drop').attr('data-word', word);
cell.textContent = word[k];
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
Thanks

Hope this help you :
var listOfWords = [];
var ul = document.getElementById("wordlist");
var i;
for(i = 0; i < ul.children.length; ++i){
listOfWords.push({
"name" : ul.children[i].getAttribute("data-word"),
"pic" : ul.children[i].getAttribute("data-pic"),
"audio" : ul.children[i].getAttribute("data-audio")
});
console.log(listOfWords);
}
console.log(listOfWords);
var chosenWords = [];
var cpy_list = listOfWords.slice();
for(var x = 0; x < 6; x++)
{
var rand = Math.floor(Math.random() * (cpy_list.length));
console.log('push ' + cpy_list[rand].name);
chosenWords.push(cpy_list[rand].name);
cpy_list.splice(rand,1);
console.log(cpy_list);
if (chosenWords.length < 12){
console.log('make a blanck' );
chosenWords.push(' ');
}
}
console.log(chosenWords);
var shuffledWords = [];
shuffledWords = chosenWords.sort(function() { return 0.5 - Math.random() });
var guesses = {};
console.log(shuffledWords);
var tbl = document.createElement('table');
tbl.className = 'tablestyle';
var wordsPerRow = 2;
for (var i = 0; i < shuffledWords.length - 1; i += wordsPerRow) {
var row = document.createElement('tr');
console.log(shuffledWords);
for (var j = i; j < i + wordsPerRow; ++j) {
var word = shuffledWords[j];
console.log(j);
console.log(word);
guesses[word] = [];
for (var k = 0; k < word.length; ++k) {
var cell = document.createElement('td');
$(cell).addClass('drop').attr('data-word', word);
cell.textContent = word[k];
row.appendChild(cell);
}
}
tbl.appendChild(row);
}
document.body.appendChild(tbl);
$('#pickNext').click(function() {
// remove the class from all td's
$('td').removeClass('spellword');
// pick a random word
rndWord = Math.floor(Math.random() * (listOfWords.length));
// apply class to all cells containing a letter from that word
$('td[data-word="' + listOfWords[rndWord].name + '"]').addClass('spellword');
});
$('.drag').draggable({
helper: 'clone',
snap: '.drop',
grid: [60, 60],
revert: 'invalid',
snapMode: 'corner'
});
$('.drop').droppable ({
drop: function(event, ui) {
word = $(this).data('word');
guesses[word].push($(ui.draggable).attr('data-letter'));
console.log($(event));
console.log($(ui.draggable).text());
console.log('CHECKING : ' + $(this).text() + ' against ' + $(ui.draggable).text().trim());
if ($(this).text() == $(ui.draggable).text().trim()) {
$(this).addClass('wordglow3');
} else {
$(this).addClass('wordglow');
}
console.log('CHECKING : ' + $(this).text() + ' against ' + $(ui.draggable).text().trim());
console.log(guesses);
if (guesses[word].length == 3) {
if (guesses[word].join('') == word) {
$('td[data-word=' + word + ']').addClass('wordglow2');
} else {
$('td[data-word=' + word + ']').addClass("wordglow4");
guesses[word].splice(0, guesses[word].length);
}
}
},
activate: function(event, ui) {
word = $(this).data('word');
// try to remove the class
$('td[data-word=' + word + ']').removeClass('wordglow').removeClass('wordglow4').removeClass('wordglow3');
}
});
$(".minibutton").hover(function (){
$(this).css("text-decoration", "underline");
},function(){
$(this).css("text-decoration", "none");
}
);
$(".minibutton2").hover(function (){
$(this).css("text-decoration", "underline");
},function(){
$(this).css("text-decoration", "none");
}
);
var audio = $("#mysoundclip")[0];
$("button").click(function() {
var noExist = $('td[data-word=' + listOfWords[rndWord].name + ']').hasClass('wordglow2');
if (noExist) {
$('#pickNext').click();
} else {
$("#mysoundclip").attr('src', listOfWords[rndWord].audio);
audio.play();
}
});
var audio = $("#mysoundclip")[0];
$("button2").click(function() {
var noExist = $('td[data-word=' + listOfWords[rndWord].name + ']').hasClass('wordglow2');
if (noExist) {
$('#pickNext').click();
} else {
$("#mysoundclip").attr('src', listOfWords[rndWord].audio);
audio.play();
}
});
var pic = $("#mypic")[0];
$("button").click(function() {
var noExist = $('td[data-word=' + listOfWords[rndWord].name + ']').hasClass('wordglow2');
if (noExist) {
$('#pickNext').click();
} else {
pic = $("#mypic").attr('src', listOfWords[rndWord].pic);
pic.show();
}
});
function keys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
}
​

First you should change :
If(chosenWords.length < 12){
to :
if (chosenWords.length < 12) {
and :
chosenWords.push(“ ”);
to :
chosenWords.push(' ');
and define the variable chosenWords.

Related

Execute function on each element (with the same id)

I have this HTML code:
<div id="dadosalvaje" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>1</dd></dl></div>
<div id="dadosalvaje" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>3</dd></dl></div>
And i want to execute this JavaScript code on each one:
$(document).ready(function() {
//Arreglos
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var contenedor = $('#dadosalvaje');
var texto = contenedor.text().split(' ');
var resultado = texto.pop();
var zonaID = $('#dadosalvaje').attr('class');
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
contenedor.append('<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>');
contenedor.attr('id', 'salvajelisto');
}
}
});
It just affects the first element and I can't find the way to modify both of them.
Is there any way to modify every single element with the same ID ?
First you need to make unique id
You do not need the "draconistone" class
Inside the $(document).ready(function() { and }); tags make the code a function with an id parameter like this:
function name(id) {
//Arreglos
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var contenedor = $('#' + id);
var texto = contenedor.text().split(' ');
var resultado = texto.pop();
var zonaID = $('#' + id).attr('class');
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
contenedor.append('<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>');
contenedor.attr('id', 'salvajelisto');
}
}
}
Then execute the functions with the two different ids as parameters.
Maybe you can use $.each()
Like this
$('.draconistone').each(function() {
var zonaID = $(this).attr('class');
..
});
There is one for the same class
$( document).ready(function() {
$( ".draconistone" ).each(function( i ) {
var zonas = ['draconistone','cessabit', 'valoran'];
var draconistone = ['bulbasaur', 'pikachu', 'squirtle'];
//Variables
var texto = this.innerText.split(' ');
var resultado = texto.pop();
var zonaID = this.className;
for (var i = 0; i < zonas.length; i++) {
if (zonaID == zonas[i]) {
if (zonaID == 'draconistone') {
var pokemonSprite = draconistone[resultado - 1];
}
}
}
for (var i = 0; i < zonas.length; i++) {
if (zonas[i] == zonaID) {
this.innerHTML += '<img src="https://www.pkparaiso.com/imagenes/xy/sprites/animados/' + pokemonSprite + '.gif"><div class="salvajeNombre">' + pokemonSprite + '</div>';
this.id = 'salvajelisto';
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dadosalvaje1" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>1</dd></dl></div>
<div id="dadosalvaje2" class="draconistone"><dl class="codebox"><dd><strong>Número aleatorio (1,10) : </strong>3</dd></dl></div>

pagination wrong progress of numbers

This is my Code:
var pages = Math.ceil(allItems / itemsPerPage);
var pagesArray = [];
for(var i = 0; i < pages; i++){
pagesArray.push(i);
}
var show = 3;
var offset = pageCounter + show;
var showPages = pagesArray.slice(pageCounter, offset);
for(var h = 0; h < showPages.length; h++){
if(pageCounter == showPages[h]){
selectedPageClass = 'selected';
}else{
selectedPageClass = '';
}
$(".pagination").append("<a href='#' class='" + selectedPageClass +"'>" + showPages[h] + "</a>");
}
My Problem now is:
if I have this array ["1","2","3","4","5"]
First Step when I am on page "0" it should be :
1(selected) 2 3
this works. but than it goes on like this:
2(selected) 3 4
3(selected) 4 5
4(selected) 5
5(selected)
But what I want is this:
1(selected) 2 3
2(selected) 3 4
3(selected) 4 5
3 4(selected) 5
3 4 5(selected)
http://codepen.io/anon/pen/JbBYva
You can update the variables on the top, the pageCounter is 0-based.
//editable variables
var pages = 5;
var pageCounter = 0;
var show = 3;
//calculation
var pagesArray = [];
for(var i = 1; i <= pages; i++){
pagesArray.push(i);
}
var offset = pageCounter + show;
var showPages = pagesArray.slice(Math.min(pages - show, pageCounter), offset);
for(var h = 0; h < showPages.length; h++){
if(pageCounter + 1 == showPages[h]){
selectedPageClass = 'selected';
}else{
selectedPageClass = '';
}
$(".pagination").append("<a href='#' class='" + selectedPageClass +"'>" + showPages[h] + "</a>");
}
You should do your showPages like this:
var showPages = pagesArray.slice(Math.min(pageCounter, pages- show), offset);
See demo below:
var pages = 10,
pageCounter = 0;
var pagesArray = [];
for (var i = 0; i < pages; i++) {
pagesArray.push(i);
}
var show = 3;
function paginate() {
$(".pagination").empty();
var offset = pageCounter + show;
var showPages = pagesArray.slice(Math.min(pageCounter, pages - show), offset);
for (var h = 0; h < showPages.length; h++) {
if (pageCounter == showPages[h]) {
selectedPageClass = 'selected';
} else {
selectedPageClass = '';
}
$(".pagination").append("<a href='#' class='" + selectedPageClass + "'>" + showPages[h] + "</a>");
}
}
// initialize
paginate();
// turn pages
$('#counter').click(function() {
if (pageCounter >= pages)
return;
pageCounter++;
paginate();
});
// restart pagination
$('#restart').click(function() {
pageCounter = 0;
paginate();
});
.selected {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pagination"></div>
<button id="counter">Turn a page</button>
<button id="restart">Restart</button>

Keep the clicked objects in an array in javascript

I made a puzzle game in javascript. I have made objects to keep some attributes relevant to the each pazzle squares. I want to get the object id which is relevant to the onclick.(not the div id). How to get the specific object id relevant to the clicked div?
window.onload = function() {
createDivs();
objects();
random();
onclickeventHanlder(event);
};
var getId;
var x = 3;
var counting = 0;
var tileSize = 600 / x;
var array2 = [];
var object = [];
function createDivs() {
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var id = i + "" + j;
var element = document.createElement('div');
element.setAttribute("class", "pieces");
element.setAttribute("id", id);
element.style.width = 600 / x + "px";
element.style.height = 600 / x + "px";
element.style.margin = "0px auto";
element.style.overflow = "hidden";
element.setAttribute("onclick", "onclickeventHanlder(this)");
if (count > 0) { // to break row-wise
if (i == count && j == 0) {
element.style.clear = "both";
}
}
element.style.float = "left";
document.getElementById('puzzle-body').appendChild(element);
}
count++;
}
}
function objects(){
var count = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var objName = new Object();
objName.position = -(j * tileSize) + "px" + " " + -(i * tileSize) + "px";
objName.divID = document.getElementById(i + "" + j);
objName.id = count;
if(count<x*x-1){
objName.state = true; // if image is there
}else{
objName.state = false; // if image isn't there
}
object[count] = objName;
count++;
}
}
}
function reset(){
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
var obj = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj.position;
}
looping++;
}
}
}
function random(){
var array = [];
while (array.length < ((x * x) - 1)) {
var randomnumber = Math.floor(Math.random() * ((x * x) - 1));
var found = false;
for (var i = 0; i < array.length; i++) {
if (array[i] == randomnumber) {
found = true;
break;
}
}
if (!found) {
array[array.length] = randomnumber;
}
}
var looping = 0;
for (var i = 0; i < x; i++) {
for (var j = 0; j < x; j++) {
if (looping < x * x-1) {
var random = array[looping];
var obj = object[random];
var obj2 = object[looping];
if(obj.id<8){
var urlString = 'url("../images/Golden.jpg")';
obj.divID.style.backgroundImage = urlString;
obj.divID.style.backgroundPosition = obj2.position;
}
}
looping++;
}
}
}
function onclickeventHanlder(event) {
var pos = event;
}

making groups with random names in it in javascript

I am new to coding Javascript. I am trying to to shuffle list of names inputted on a textarea. The user selects the number of groups desired, and shuffle on click, then show the divided groups as output result. Below is my code but it is not working as it should be, pls help!
<script>
function ArrayToGroups(source, groups){
var groupList = [];
groupSize = Math.ceil(source.length/groups);
var queue = source;
for(var r = 0; r < groups; r++){
groupList.push(queue.splice(0,groupSize));
}
return groupList;
}
function textSpliter(splitText){
var textInput = document.getElementById("inputText").value;
var splitText = textInput.split(',');
var newList = [];
for(x = 0; x <= splitText.length; x++) {
var random = Math.floor(Math.random() * splitText.length);
var p = splitText[random];
newList.push(p);
splitText.splice(p,groupList);
}
for(var i = 0; i < newList.length; i++){
var s = newList[i];
document.getElementById('resInput').value += s + "\n" ;
}
return splitText;
}
</script>
Below is my input and output textareas
</head>
<body>
<form>
<textarea id="inputText" placeholder="text" rows="10" cols="40"></textarea>
<input type="number" name="number" max="6" value="1" id="groupNumber">
<textarea id="resInput" placeholder="text" rows="10" cols="40"></textarea>
<input type="button" name="Shuffle" value="shuffle" onclick="textSpliter()">
</form>
</body>
</html>
function shuffle() {
// Get list
// Example: element1, element 2, ele ment 3, ...
var list = document.getElementById("inputText").value.replace(/\s*,\s*/g, ",").split(",");
// Get number of groups
var n = parseInt(document.getElementById("groupNumber").value);
// Calculate number of elements per group
var m = Math.floor(list.length / n);
// Enought elements
if (n * m == list.length) {
// Create groups
var groups = new Array();
for (i = 0; i < n; i++) {
groups[i] = new Array();
for (j = 0; j < m; j++) {
// Random
rand = Math.floor(Math.random() * list.length);
// Add element to group
groups[i][j] = list[rand];
// Remove element to list
list.splice(rand, 1);
}
}
// Output
var text = "";
for (i = 0; i < n; i++) {
text += "Group " + (i + 1) + ": ";
for (j = 0; j < m; j++) {
if (j != 0) { text += ", "; }
text += groups[i][j];
}
text += "\n";
}
document.getElementById("resInput").value = text;
} else {
alert("Add more elements");
}
}
I rewrote your code. It's pretty self-explanatory.
FIDDLE
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [];
for (var i = 0; i < groupCount; i++) {
var group = [];
for (var j = 0; j < groupSize; j++) {
var random = Math.floor(Math.random() * names.length);
var name = names[random];
if (name != undefined) {
group.push(name);
names.splice(names.indexOf(name), 1);
}
}
group.sort();
groups.push(group);
}
printGroups(groups);
}
function printGroups(group) {
var output = document.getElementById("resInput");
output.value = "";
for (var i = 0; i < group.length; i++) {
var currentGroup = "";
for (var j = 0; j < group[i].length; j++) {
currentGroup = group[i].join(",");
}
output.value += currentGroup + "\r";
}
}
ES6 version ;-)
http://jsfiddle.net/dLgpny5z/1/
function textSpliter() {
var input = document.getElementById("inputText").value;
var names = input.replace(/\s*,\s*|\n/g, ",").split(",");
var groupSize = document.getElementById("groupNumber").value;
var groupCount = Math.ceil(names.length / groupSize);
var groups = [...Array(groupCount)].map(() => Array());
var i = 0
while (names.length > 0) {
var m = Math.floor(Math.random() * names.length);
groups[i].push(names[m]);
names.splice(m, 1);
i = (i >= groupCount - 1) ? 0 : i + 1
}
printGroups(groups);
}
function printGroups(groups) {
var output = document.getElementById("resInput");
output.value = groups.map(group => group.join(',')).join('\r');
}

Dynamically replacing the content for large list

I am trying to render child elements of an element if the element is in view or removing the content if not in view like below on scroll event like below
list.addEventListener('scroll', function () {
var elements = document.querySelectorAll('.aBox');
var toBe = counter - 1 - elements.length;
for (var i = 0; i < elements.length; i++) {
var inView = visibleY(elements[i]),
ele = elements[i].querySelector('.item');
if (inView === false && ele) {
console.log("Not in visible, keeping it none");
var height = elements[i].clientHeight;
elements[i].style.height = height + "px";
elements[i].innerHTML = "";
} else if(!ele){
console.log('Placing the content');
var minArray = arr[toBe + 1 + i],
str = "";
for (var j = 0; j < minArray.length; j++) {
str += "<div class='item'>" + minArray[j] + "</div>";
}
elements[i].innerHTML = str;
}
}
});
It seems working but if I have a look at the DOM this is not working as expected. Someone please help me to find the problem, fiddle.
Update
function updateData(callback) {
var elements = document.querySelectorAll('.aBox');
elements = Array.prototype.slice.call(elements);
var toBe = counter - 1 - elements.length;
async.each(elements, function (element, cb) {
var inView = $(element).is_on_screen(),
ele = element.querySelector('.item');
if (inView == false && ele) {
console.log("Not in visible, keeping it none");
var height = element.clientHeight;
element.style.height = height + "px";
element.innerHTML = "";
} else if (!ele && inView) {
console.log('Placing the content');
var minArray = arr[toBe + 1 + i],
str = "";
if (typeof minArray === "object") {
for (var j = 0; j < minArray.length; j++) {
str += "<div class='item'>" + minArray[j] + "</div>";
}
element.innerHTML = str;
}
}
cb();
}, function () {
callback()
});
}
Fiddle
Hi I have solved this problem. Posting here, so that it will be more helpful for people who want to work on mobiles to display very large lists with virtual scrolling
var arr = new Array(10000);
for (var i = 0; i < arr.length; i++) {
arr[i] = "Hello Dudes..." + i;
}
Array.prototype.chunk = function (chunkSize) {
var array = this;
return [].concat.apply([],
array.map(function (elem, i) {
return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
}));
}
arr = arr.chunk(50);
var list = document.getElementById('longList');
var button = document.getElementById('loadMore');
var counter = arr.length,
aBoxLen = 1;
function appendBox() {
var div = document.createElement('div'),
str = "";
div.className = "aBox";
var minArray = arr[counter - aBoxLen];
for (var i = 0; i < minArray.length; i++) {
str += "<div class='item'>" + minArray[i] + "</div>";
}
div.innerHTML = str;
div.setAttribute('index', counter - aBoxLen);
var box = document.querySelector('.aBox');
if (box) {
list.insertBefore(div, box);
} else {
list.appendChild(div);
}
aBoxLen += 1;
}
appendBox();
button.addEventListener('click', function () {
appendBox();
});
$.fn.is_on_screen = function () {
var win = $(window);
var viewport = {
top: win.scrollTop(),
left: win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
function updateData(callback) {
var elements = document.querySelectorAll('.aBox');
elements = Array.prototype.slice.call(elements);
var toBe = counter - 1 - elements.length;
async.each(elements, function (element, cb) {
var inView = $(element).is_on_screen(),
ele = element.querySelector('.item');
if (inView == false && ele) {
console.log("Not in visible, keeping it none");
var height = element.clientHeight;
element.style.height = height + "px";
element.innerHTML = "";
} else if (!ele && inView) {
console.log('Placing the content');
console.log(element.getAttribute('index'));
var minArray = arr[element.getAttribute('index')],
str = "";
for (var j = 0; j < minArray.length; j++) {
str += "<div class='item'>" + minArray[j] + "</div>";
}
element.innerHTML = str;
}
cb();
}, function () {
// callback()
});
}
var delay = false;
var timeout = null;
list.addEventListener('touchmove', function () {
clearTimeout(timeout);
timeout = setTimeout(function () {
updateData();
}
}, delay);
});
None of the solutions were specifically designed for mobiles, so I have implemented this.
I think there is lots of space for improvement in this. If anybody want to improve it, please feel free to make it
Demo

Categories