two dimensional array random generator jQuery - javascript

All rows always have same numbers, why? They should take random number to populate it. Also, how can I repair it? Once I saw answer here but now I cannot find it.
var mapSizex = 5;
var mapSizey = 6;
var mapArray = [];
$(function() {
console.log("ready!");
$('#map-draw').html(drawMap());
});
function mapGenerator() {
for (i = 0; i < mapSizex; i++) {
for (x = 0; x < mapSizey; x++) {
mapArray[i, x] = getRandom(1, 5);
}
}
}
function drawMap() {
mapGenerator();
var map = '';
tileID = 0;
for (i = 0; i < mapSizex; i++) {
map = map + '<br style="clear: both;">';
for (x = 0; x < mapSizey; x++) {
map = map + '<div class="tile tileID' + tileID + '">' + mapArray[i, x] + '</div>';
tileID++;
}
}
return map;
}
function getRandom(min, max) {
var x = Math.floor((Math.random() * max) + min);
return x;
}
.tile {
float: left;
height: 20px;
width: 20px;
border: 1px solid black;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main-container">
<div id="map-container">
<div id="map-draw"></div>
</div>
</div>
To post it I need to add some more content but all included information's should be enough to find what I mean.

here is a link to JSFIDDLE woking code
It should be mapArray[i][x] and I added mapArray[i]=[]; in the outer loop.
here is your fixed code:
var mapSizex=5;
var mapSizey=6;
var mapArray=[];
$(function() {
console.log( "ready!" );
$('#map-draw').html(drawMap());
});
function mapGenerator(){
for(i=0;i<mapSizex;i++){
mapArray[i]=[];
for(x=0;x<mapSizey;x++){
mapArray[i][x]= getRandom(1,5);
console.log(i,x,getRandom(1,5))
}
}
}
function drawMap(){
mapGenerator();
console.log(mapArray)
var map='';
tileID=0;
for(i=0;i<mapSizex;i++){
map=map+'<br style="clear: both;">';
for(x=0;x<mapSizey;x++){
map=map+'<div class="tile tileID'+tileID+'">'+mapArray[i][x]+'</div>';
tileID++;
}
}return map;
}
function getRandom(min,max) {
var x = Math.floor((Math.random() * max) + min);
return x;
}

Related

When i use own sleep() function in javascript my recurency sorting function using quick sorting algorithm doesnt work

Hey I'm a beginner in js. I wanted to do quick sorting function. I have tables with values ​​and I would like to show how they change to show how the function works. Unfortunately the function is almost instantaneous so I did sleep function and added to the sorting function. After that the function didn't work in some cases (some values ​​were unsorted) I think it might have something to do with recursion. Please help how can i do it better? :)
(Other functions like selection sort or bubble sort works properly)
var arr = new Array();
Array.prototype.swap = function (x,y) {
var temp = this[x];
this[x] = this[y];
this[y] = temp;
return this;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function start_qs(){
for(i=0;i<10;i++){
var value = Math.floor(Math.random() * 100); // random integer from 0 - 100
arr[i] = value;
}
qs(arr, 0, arr.length - 1);
}
function update(effect_id, array){
document.getElementById(effect_id).innerHTML = "";
for(i=0;i<10;i++){
document.getElementById(effect_id).innerHTML += '<div class="label" style="height:'+array[i]+'px;">'+array[i]+'</div>';
}
}
async function qs(array, left, right){
let i = left;
let j = right;
x = array[Math.floor((left+right)/2)];
while(i<=j){
await sleep(50);
while(array[i] < x && i < right){i++;}
while(array[j] > x && j > left){j--;}
if(i <= j){
array.swap(i,j);
i++;
j--;
update("quicksort", arr);
}
}
if(left < j){qs(array, left, j);}
if(i < right){qs(array, i, right);}
}
window.onload = function(){start_qs();}
:root {
--main: #202020;
--sec: #D03737;
}
html{
background: var(--main);
color: var(--sec);
font-size: 28px;
}
body {
margin: 0;
padding: 0;
}
h3{text-align:center;}
.element{margin:auto;width:70%;}
.effect{width:60%;height:200px;margin:auto;}
.label{background: var(--sec); width:7%;margin:0 1.5%;color:black;text-align:center;font-size:0.75rem;}
<script type="text/javascript" src="js/quickSort.js"/></script>
<h2 style="text-align:center;">Javascript algorithms</h2>
<div class="element" id="quicksorting" >
<h3>Quick Sorting
<button style="border-radius:10px;padding:10px 30px;background:var(--main);border-color:var(--sec);color:var(--sec);" onclick="start_qs()">Restart</button></h3>
<div class="content" style="display:flex;">
<div class="effect" id="quicksort" style="display:flex;align-items:flex-end;">
</div>
</div>
</div>
Since you're calling the function recursively, you need to use await in the recursive calls. Otherwise the recursive calls will not execute until the current call finishes, and quicksort requires things all the recursive calls to execute in order.
Also declare x as a local variable, otherwise the recursive calls will overwrite its value.
var arr = new Array();
Array.prototype.swap = function(x, y) {
var temp = this[x];
this[x] = this[y];
this[y] = temp;
return this;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function start_qs() {
for (i = 0; i < 10; i++) {
var value = Math.floor(Math.random() * 100); // random integer from 0 - 100
arr[i] = value;
}
qs(arr, 0, arr.length - 1);
}
function update(effect_id, array) {
document.getElementById(effect_id).innerHTML = "";
for (let i = 0; i < 10; i++) {
document.getElementById(effect_id).innerHTML += '<div class="label" style="height:' + array[i] + 'px;">' + array[i] + '</div>';
}
}
async function qs(array, left, right) {
let i = left;
let j = right;
let x = array[Math.floor((left + right) / 2)];
while (i <= j) {
await sleep(50);
while (array[i] < x && i < right) {
i++;
}
while (array[j] > x && j > left) {
j--;
}
if (i <= j) {
array.swap(i, j);
i++;
j--;
update("quicksort", arr);
}
}
if (left < j) {
await qs(array, left, j);
}
if (i < right) {
await qs(array, i, right);
}
}
window.onload = function() {
start_qs();
}
:root {
--main: #202020;
--sec: #D03737;
}
html {
background: var(--main);
color: var(--sec);
font-size: 28px;
}
body {
margin: 0;
padding: 0;
}
h3 {
text-align: center;
}
.element {
margin: auto;
width: 70%;
}
.effect {
width: 60%;
height: 200px;
margin: auto;
}
.label {
background: var(--sec);
width: 7%;
margin: 0 1.5%;
color: black;
text-align: center;
font-size: 0.75rem;
}
<script type="text/javascript" src="js/quickSort.js" /></script>
<h2 style="text-align:center;">Javascript algorithms</h2>
<div class="element" id="quicksorting">
<h3>Quick Sorting
<button style="border-radius:10px;padding:10px 30px;background:var(--main);border-color:var(--sec);color:var(--sec);" onclick="start_qs()">Restart</button></h3>
<div class="content" style="display:flex;">
<div class="effect" id="quicksort" style="display:flex;align-items:flex-end;">
</div>
</div>
</div>

Slider Show does not works as ment to be- can't seem to find the problem

I want to create a slidershow made of some divs in a container. for some reason the slider messes everything up. Would appreciate any help with it.
$('[class^=show]').fadeOut(0)
var curClass = 3
var className = 'show-'
var fadeTime = 1000
var showTime = 3000
var cycleTime = (fadeTime * 2 + showTime) * (curClass + 1);
setInterval(function() {
for (var i = 0; i <= curClass; i++) {
cls = '.' + className + i;
// $(cls).fadeIn(fadeTime).delay(showTime).fadeOut(fadeTime);
$(cls).fadeIn(fadeTime, function() {
sleep(showTime);
$(cls).fadeOut(fadeTime);
});
}
}, cycleTime);
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
.container div {
height: 50px;
width: 50px;
background: red;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='container'>
<div class="show-0">Hey 0</div>
<div class="show-1">Hey 1</div>
<div class="show-2">Hey 2</div>
<div class="show-3">Hey 3</div>
</div>
the slider should show each time one class of 'show-X' in order, fading in and out nicely.
Please see following:
$(document).ready(function () {
$('[class*=show-]').fadeOut(0);
var curClass = 3
var className = 'show-'
var fadeTime = 500
var showTime = 1000
var cycleTime = [(fadeTime * 2 + showTime) * (curClass + 1)] / 4;
var i = 0;
console.log(cycleTime);
setInterval(function () {
$('.' + className + i).fadeIn(fadeTime, function () {
//sleep(showTime);
try {
if (i == 0) { $('.' + className + curClass).fadeOut(fadeTime); } else { $('.' + className + (i-1)).fadeOut(fadeTime); }
} catch (e) { }
});
if (i == 3) { i = 0; } else { i++; }
}, showTime);
});
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
.container div {
height: 50px;
width: 50px;
background: red;
color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='container'>
<div class="show-0">Hey 0</div>
<div class="show-1">Hey 1</div>
<div class="show-2">Hey 2</div>
<div class="show-3">Hey 3</div>
</div>

I couldn't display random images without duplicates

hi i'm working on a task which will display random images. The code that i have shows random images but actually i want to display random images without duplicates. How to get this done. Help me. Thanks in advance.
var images = ['https://cdn.paperindex.com/banner/advertisement/1.jpeg', 'https://cdn.paperindex.com/banner/advertisement/2.jpeg', 'https://cdn.paperindex.com/banner/advertisement/3.jpeg', 'https://cdn.paperindex.com/banner/advertisement/4.jpeg'];
var imagesused = [];
$('.advertisement div').each(function() {
var rand = Math.floor(Math.random() * images.length);
$(this).append('<img src="' + images[rand] + '"/>');
if (imagesused.indexOf(images[rand]) != -1) images.splice(rand, 1);
else imagesused.push(images[rand]);
});
.advertisement div img {
width: 100px;
height: 100px;
margin-right: 10px;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="advertisement">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
Make a copy of original array. And after adding the random image remove it from copy of array.You don't need to create imagesUsed as you removing it from the array.
var images = ['https://cdn.paperindex.com/banner/advertisement/1.jpeg', 'https://cdn.paperindex.com/banner/advertisement/2.jpeg', 'https://cdn.paperindex.com/banner/advertisement/3.jpeg', 'https://cdn.paperindex.com/banner/advertisement/4.jpeg'];
//making copy of original array.
var tempImgs = images.slice(0)
$('.advertisement div').each(function() {
var rand = Math.floor(Math.random() * tempImgs.length);
$(this).append('<img src="' + tempImgs[rand] + '"/>');
tempImgs.splice(rand, 1);
});
.advertisement div img {
width: 100px;
height: 100px;
margin-right: 10px;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="advertisement">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
My approach would be like this, this way is can randomize them no matter how small or big your array is
first create a method which shuffle them
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
and then you use it before looping your array
images = shuffle(images);
var images = ['https://cdn.paperindex.com/banner/advertisement/1.jpeg', 'https://cdn.paperindex.com/banner/advertisement/2.jpeg', 'https://cdn.paperindex.com/banner/advertisement/3.jpeg', 'https://cdn.paperindex.com/banner/advertisement/4.jpeg'];
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
images = shuffle(images);
var imagesused = [];
$('.advertisement div').each(function(x) {
$(this).append('<img src="' + images[x] + '"/>');
});
.advertisement div img {
width: 100px;
height: 100px;
margin-right: 10px;
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="advertisement">
<div></div>
<div></div>
<div></div>
<div></div>
</div>

Getting back correct index value from Array

I have to show Array values in circle kind of shape and it has to be run in a loop forever. Things are working fine when you rotate circle counter clockwise. But it has a problem in when we move circle in opposite direction.
I have an active element on the wheel. So when you user clicks on any other slide then active it calculates the difference between clicked slide and active slide then add and remove items in wheel accordingly.
So basically it picks the value from Array. if you move circle clockwise it picks values from the back of the Array and if you move it counterclockwise it starts picking up values from next available. If 11 items are rendered in first-page load then it will start taking values from 12 no index.
The problem occurs when you click the item which has above position from the active element and then you again rotates it counterclockwise.
Let say you click item no. 8 then you click item no.7. In this case item, no.2 should have been added into the wheel.
Here is fiddle.
var numberOfElement = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];
var initialRender = numberOfElement.slice(0, 11);
var startPoint = initialRender.length;
var endPoint = numberOfElement.length;
function generateHtml() {
var html = '';
initialRender.forEach(function(item, index) {
var angle = 18 * (index);
var className = angle === 90 ? 'active' : '';
html += '<div class="shapes ' + className + '" data-deg="' + angle + '" style="--deg:' + angle + 'deg;"> <span class="set-pos">' + (item) + '</span> <span> ' + angle + ' deg </span></div>';
})
document.querySelector('#dynamic-html').innerHTML = html;
}
generateHtml();
$('#dynamic-html').on('click', '.shapes', function() {
var deg = 90;
var activeDeg = $('.active').data('deg');
var needToremoveElement = activeDeg;
var selectedElement = $(this).data('deg');
var degrees = deg - selectedElement;
var diff = Math.abs((activeDeg - selectedElement) / 18);
$('.shapes').removeClass('active');
$(this).addClass('active');
var movementCloseWise = degrees > ($('.circle').data('deg') || 0);
$('.circle').removeData('deg');
$('.circle').css({
'transform': 'rotate(' + degrees + 'deg)'
}).attr('data-deg', degrees);
if (movementCloseWise) {
var itemLength = $('.shapes').length;
$('.shapes:gt(' + ((itemLength - 1) - diff) + ')').remove()
var newItems = generateItem(getItemsFromBack(diff), true);
newItems = $(newItems).get().reverse();
$('#dynamic-html').prepend(newItems)
startPoint -= diff;
} else {
var newItems = generateItem(getItemFromStart(diff), false)
$('#dynamic-html').append(newItems)
$('.shapes:lt(' + (diff) + ')').remove()
endPoint += diff;
}
})
function getItemsFromBack(length) {
var values = [];
endPoint = endPoint - length;
if (endPoint < 0) {
endPoint = numberOfElement.length - Math.abs(endPoint)
var otherVal = 0;
if (endPoint + length >= numberOfElement.length) {
otherVal = (endPoint + length) - numberOfElement.length;
values = numberOfElement.slice(endPoint, numberOfElement.length)
}
if (otherVal > 0) {
values = values.concat(numberOfElement.slice(0, otherVal))
}
} else {
values = numberOfElement.slice(endPoint, endPoint + length)
}
var valuesCount = values.length;
return values.reverse();
}
function getItemFromStart(length) {
var values = numberOfElement.slice(startPoint, startPoint + length);
var valueCount = values.length;
startPoint += valueCount;
if (valueCount < length) {
startPoint = 0;
return values.concat(getItemFromStart(length - valueCount));
} else if (startPoint >= numberOfElement.length) {
startPoint = 0;
}
return values;
}
function generateItem(items, isClockWise) {
var html = "",
lastItemAngle;
if (isClockWise) {
lastItemAngle = $('#dynamic-html .shapes:first').data('deg');
} else {
lastItemAngle = $('#dynamic-html .shapes:last').data('deg');
}
items.forEach(function(item, index) {
if (isClockWise) {
var angles = lastItemAngle - (18 * (index + 1))
} else {
var angles = lastItemAngle + (18 * (index + 1))
}
html += '<div class="shapes" data-deg="' + (angles) + '" style="--deg:' + angles + 'deg;"> <span class="set-pos">' + (item) + '</span> <span> ' + angles + ' deg </span></div>';
});
return html;
}
I think your problem is just your endPoint initialization value. In your code, you initialize it as var endPoint = numberOfElement.length; which is wrong( I think) and it should be initialized by 0; I changed it and it worked:
var numberOfElement = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30];
var initialRender = numberOfElement.slice(0,11);
var startPoint = initialRender.length;
var endPoint = 0; /* here is the change */
function generateHtml(){
var html ='';
initialRender.forEach(function(item,index){
var angle = 18 * (index);
var className = angle === 90? 'active':'';
html+='<div class="shapes '+className+'" data-deg="'+angle+'" style="--deg:'+angle+'deg;"> <span class="set-pos">'+(item)+'</span> <span> '+angle+' deg </span></div>';
})
document.querySelector('#dynamic-html').innerHTML= html;
}
generateHtml();
$('#dynamic-html').on('click','.shapes',function(){
var deg = 90;
var activeDeg = $('.active').data('deg');
var needToremoveElement = activeDeg;
var selectedElement = $(this).data('deg');
var degrees = deg - selectedElement;
var diff = Math.abs((activeDeg - selectedElement) / 18);
$('.shapes').removeClass('active');
$(this).addClass('active');
var movementCloseWise = degrees > ($('.circle').data('deg') || 0);
$('.circle').removeData('deg');
$('.circle').css({'transform' : 'rotate('+ degrees +'deg)'}).attr('data-deg',degrees);
if(movementCloseWise){
var itemLength = $('.shapes').length;
$('.shapes:gt('+((itemLength-1)-diff)+')').remove()
var newItems = generateItem(getItemsFromBack(diff), true);
newItems = $(newItems).get().reverse();
$('#dynamic-html').prepend(newItems)
startPoint -= diff;
}else{
var newItems = generateItem(getItemFromStart(diff), false)
$('#dynamic-html').append(newItems)
$('.shapes:lt('+(diff)+')').remove()
endPoint += diff;
}
})
function getItemsFromBack(length) {
var values = [];
endPoint = endPoint - length;
if (endPoint < 0) {
endPoint = numberOfElement.length - Math.abs(endPoint)
var otherVal = 0;
if (endPoint + length >= numberOfElement.length) {
otherVal = (endPoint + length) - numberOfElement.length;
values = numberOfElement.slice(endPoint, numberOfElement.length)
}
if (otherVal > 0) {
values = values.concat(numberOfElement.slice(0, otherVal))
}
} else {
values = numberOfElement.slice(endPoint, endPoint + length)
}
var valuesCount = values.length;
return values.reverse();
}
function getItemFromStart(length) {
var values = numberOfElement.slice(startPoint, startPoint + length);
var valueCount = values.length;
startPoint += valueCount;
if (valueCount < length) {
startPoint = 0;
return values.concat( getItemFromStart(length - valueCount) );
} else if (startPoint >= numberOfElement.length) {
startPoint = 0;
}
return values;
}
function generateItem (items, isClockWise){
var html = "", lastItemAngle;
if(isClockWise){
lastItemAngle = $('#dynamic-html .shapes:first').data('deg');
}
else{
lastItemAngle = $('#dynamic-html .shapes:last').data('deg');
}
items.forEach(function(item,index){
if(isClockWise){
var angles = lastItemAngle - (18 * (index +1))
}
else{
var angles = lastItemAngle + (18 * (index +1))
}
html+='<div class="shapes" data-deg="'+(angles)+'" style="--deg:'+angles+'deg;"> <span class="set-pos">'+(item)+'</span> <span> '+angles+' deg </span></div>';
});
return html;
}
.main{
display: flex;
justify-content: center;
align-items: center;
height: 500px;
}
.pos{
height:150px;
width:150px;
position: relative;
}
.circle{
background: red;
height:150px;
width:150px;
border-radius: 50%;
transition: transform 0.3s ease-in-out;
}
.shapes{
position: absolute;
top:calc(50% - 75px);
left:calc(50% - 10px);
width: 20px;
height: 150px;
transform: rotate(var(--deg)) translate(0, 160px);
background: green;
text-align: center;
}
.fake-overlay{
position: absolute;
width: 203%;
height: 320%;
background: #fff;
top: -160px;
right: -148%;
display: none
}
.active{
background: red
}
.set-pos{
position: absolute;
bottom: 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div class="pos">
<div class="circle">
<div id="dynamic-html"></div>
</div>
<div class="fake-overlay"></div>
</div>
</div>
And here is Jsfiddle
I have fixed this by the following code.
function getItemsFromBack(length) {
var values = [];
if (endPoint > numberOfElement.length) {
var diff = endPoint - numberOfElement.length;
values = numberOfElement.slice(diff - length, diff)
endPoint = endPoint - length;
return values.reverse();
}
endPoint = endPoint - length;
if (endPoint < 0) {
endPoint = numberOfElement.length - Math.abs(endPoint)
var otherVal = 0;
if (endPoint + length >= numberOfElement.length) {
otherVal = (endPoint + length) - numberOfElement.length;
values = numberOfElement.slice(endPoint, numberOfElement.length)
}
if (otherVal > 0) {
values = values.concat(numberOfElement.slice(0, otherVal))
}
} else {
values = numberOfElement.slice(endPoint, endPoint + length)
}
var valuesCount = values.length;
return values.reverse();
}
I am checking if endPoint is greater then total Array length. Then endPoint- Array.length and using diff to get the element
Your CSS is awesome, but your JavaScript still has a bug. Try this:
click 7, then click 2
To fix it, I propose we simplify your logic a bit:
give meaningful ids to items so we can easily select them, compare them and deduce the item angle
do not use hard coded arrays (if you did it because of a code quality tool like jslint, consider telling it to tolerate for loops)
The complexity of your code was coming from the management of start and end points within a range of 1-30. This is now made easy by 1st point above.
I have not changed your code too much so you can recognize your working parts easily:
// Global variables
var numberOfItems = 30,
numberOfRenderedItems = 11,
firstItem = 0
;
function generateHtml(){
var html ='';
for (var item = 0; item < numberOfRenderedItems; item++) {
var angle = 18 * item,
className = angle === 90? 'active':'';
html +=
'<div class="shapes '+className+'" data-item="'+item+'" data-deg="'+angle+'" style="--deg:'+angle+'deg;">'+
' <span class="set-pos">'+(item+1)+'</span>'+
' <span>'+angle+' deg </span>'+
'</div>';
}
document.querySelector('#dynamic-html').innerHTML= html;
}
generateHtml();
$('#dynamic-html').on('click','.shapes',function(){
// Set clicked item active
$('.shapes').removeClass('active');
$(this).addClass('active');
var selectedItem = Number($(this).data('item')),
previousActiveItem = firstItem + Math.floor(numberOfRenderedItems/2),
diff = selectedItem - previousActiveItem,
selectedAngle = selectedItem * 18,
degrees = 90 - selectedAngle,
isClockWise = diff < 0;
// Rotate all items
$('.circle').removeData('deg');
$('.circle').css({'transform' : 'rotate('+ degrees +'deg)'}).attr('data-deg',degrees);
var items;
if (isClockWise)
items = getItemsFromBack(diff);
else
items = getItemsFromFront(diff);
// Remove items
items.toRemove.forEach( function (item) {
$(".shapes[data-item="+item+"]").remove();
});
// Add items
var newItems = items.toAdd.reduce( function (html, item) {
// Get item number between 1 and max
var itemNumber = getNumberInRange(item),
angle = 18 * item;
return html +
'<div class="shapes" data-item="'+item+'" data-deg="'+angle+'" style="--deg:'+angle+'deg;">'+
' <span class="set-pos">'+itemNumber+'</span>'+
' <span>'+angle+' deg </span>'+
'</div>';
}, '');
if (isClockWise)
$('#dynamic-html').append(newItems);
else
$('#dynamic-html').prepend(newItems)
})
function getItemsFromBack (diff) {
var items = {
toAdd: [],
toRemove: []
};
firstItem += diff;
for (var i = 0; i < Math.abs(diff); i++) {
items.toAdd.push(firstItem + i);
items.toRemove.push(firstItem + i + numberOfRenderedItems);
}
return items;
}
function getItemsFromFront (diff) {
var items = {
toAdd: [],
toRemove: []
};
for (var i = 0; i < Math.abs(diff); i++) {
items.toAdd.push(firstItem + i + numberOfRenderedItems);
items.toRemove.push(firstItem + i);
}
firstItem += diff;
return items;
}
function getNumberInRange (item) {
do {
item = (item + numberOfItems) % numberOfItems;
}
while (item < 0);
return item + 1;
}
Updated JSFiddle link is below
https://jsfiddle.net/dpvjtvjd/2/

using jQuery to append div's and each div has a different ID

So I'm trying to to use jQuery to append a div which will generate a card using the assigned class. The problem is I need to create a different ID each time so I can put random number on the card. I'm sure there's an easier way to do this. So i'm posing two questions. how to make the code where it put the random number on the card go endlessly. and how to append divs with unique ID's. Sorry if my code isn't the best. It's my first project.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<title></title>
<style>
.cardLook {
border: 1px solid black;
width: 120px;
height: 220px;
border-radius: 5px;
float: left;
margin: 20px;
padding: 5px;
background-color: #fff;
}
#card1,#card2,#card3,#card4,#card5 {
transform:rotate(180deg);
}
#cardTable {
background-color: green;
height: 270px
}
.reset {
clear: both;
}
</style>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
</head>
<body>
<button id="deal">Deal</button>
<button id="hit">hit</button>
<button id="stand">Stand</button>
<button id="hi">hi</button>
<div id="number"></div>
<div id="arrayOutput"></div>
<div id="someId"></div>
<div id="out2"></div>
<div id="cardTable">
</div>
<div class="reset"></div>
<script>
var what;
//Services helper functon
document.getElementById('deal').onclick = function deal() {
var score1 = Math.floor(Math.random() *10 + 1);
var score2 = Math.floor(Math.random() *10 + 1);
var firstCard = score1;
var secondCard = score2;
//myNumberArray.push(firstCard, score2);
//card1.innerHTML = myNumberArray[0];
//card2.innerHTML = myNumberArray[1];
$("#deal").click(function(){
$("#cardTable").append("<div class='cardLook' id='card1'></div>");
});
console.log(score2, score1)
}
var myNumberArray = [];
$("#hit").click(function(){
$("#cardTable").append("<div class='cardLook' id="uniqueIdNumberOne"></div>");
if (myNumberArray > 1) {
#cardTable
}
var card = Math.floor(Math.random() * 10) + 1;
document.getElementById('number').innerHTML=card;
myNumberArray.push(card);
var number = myNumberArray.value;
var arrayOutput = document.getElementById('number');
var someId = document.getElementById('someId');
someId.innerHTML = myNumberArray;
card1.innerHTML = myNumberArray[0];
card2.innerHTML = myNumberArray[1];
card3.innerHTML = myNumberArray[2];
card4.innerHTML = myNumberArray[3];
card5.innerHTML = myNumberArray[4];
// console.log("myNumberArray: ", myNumberArray);
what = calcTotal(myNumberArray);
showMe(calcTotal(myNumberArray));
});
//var output = myNumberArray = calcTotal(list);
function calcTotal(myNumberArray) {
var total = 0;
for(var i = 0; i < myNumberArray.length; i++){
total += myNumberArray[i];
}
return total;
}
//document.getElementById('out2').innerHTML = out2;
console.log("myNumberArray: ", myNumberArray);
function showMe(VAL) {
var parent = document.getElementById('out2');
parent.innerHTML = VAL;
if (calcTotal(myNumberArray) > 21) {
alert('you lose');
}
};
document.getElementById('stand').onclick = function stand() {
var compterDeal1 = Math.floor(Math.random() *10 + 1);
var computerCards = compterDeal1;
console.log(computerCards);
computerArray.push(computerCards);
if (computerCards < 21) {
stand();
}
}
var computerArray = [];
</script>
</body>
</html>
Use an unique class with all of then, and call then by class
Add a global integer:
var cardNumber = 0;
A function to generate an id:
function newCardId() {
cardNumber ++;
return 'uniqueCardId' + cardNumber.toString();
}
And use:
var newId = newCardId();
$("#cardTable").append("<div class=\"cardLook\" id=\"" + newId + "\"></div>");
Finally to access your new div:
$('#' + newId).
Note: Escape quotes within a string using backslash!

Categories