Array wont update when i JSON.stringify it - javascript

I have this code below that is able to transfer the array value to another array when i click on it. For Example, when i click on lime it will move into my Green Array The problem is after i JSON.stringify my Green Array it doesn't show the updated value.
So this is the before i add in a value my green array has 5 values.
And this is after I add in a value to my green array as you can see after I move the value in my array count increases but I don't know why when i stringify the array, it doesn't have the value I added in already I want to stringify it because I want to send the updated data to a server. Is there any reason why this is happening ?
var red = {};
var green = {};
var random = {};
var fruits = [];
var fruits1 = {["fruit"]:"Apple", ["type"]:"1"}
var fruits2 = {["fruit"]:"Tomato", ["type"]:"1"}
var fruits3 = {["fruit"]:"Lime", ["type"]:"2"}
var fruits4 = {["fruit"]:"Guava", ["type"]:"2"}
fruits.push(fruits1,fruits2,fruits3,fruits4);
var randomFruits = fruits.filter(x => x.fruit).map(x => x.fruit);
var key = "Red Fruits";
red[key] = ['Apple', 'Cherry', 'Strawberry','Pomegranate','Rassberry'];
var key2 = "Green Fruits";
green[key2] = ['Watermelon', 'Durian', 'Avacado','Lime','Honeydew'];
var key3 = "Random Fruits";
random[key3] = randomFruits;
function redraw() {
var combineString = '';
$.each(red[key], function(index) {
combineString += ('<div class="pilldiv redpill class">' + red[key][index] + '</div>');
});
$('.combineclass').html(combineString);
$.each(green[key2], function(index) {
combineString += ('<div class="pilldiv greenpill class">' + green[key2][index] + '</div>');
});
$('.combineclass').html(combineString);
var randomString = '';
$.each(random[key3], function(index) {
randomString += ('<div class="pilldiv randompill class">' + random[key3][index] + '</div>');
});
$('.randomclass').html(randomString);
}
function listener() {
$(document).ready(function() {
$(document).on("click", "#randomid div", function() {
data = this.innerHTML;
k1 = Object.keys(random).find(k => random[k].indexOf(data) >= 0)
index = random[k1].indexOf(data);
random[k1].splice(index, 1);
for (let i = 0; i < fruits.length; i++) {
if (fruits[i].fruit === data) {
if (fruits[i].type === "1") {
red[key].push(data);
} else {
green[key2].push(data);
}
}
}
$(".total_count_Green_Fruits").html(key2 + ': ' + green[key2].length);
var element = $(this).detach();
$('#combineid').prepend('<div class="new-green-fruit pilldiv class ">' + element.html() + '</div>');
});
});
$('body').on('click', 'div.new-green-fruit', function() {
data2 = this.innerHTML;
for (let i = 0; i < fruits.length; i++) {
if (fruits[i].fruit === data2) {
if (fruits[i].type === "1") {
k2 = Object.keys(red).find(k => red[k].indexOf(data2) >= 0);
index2 = red[k2].indexOf(data2);
red[k2].splice(index2, 1);
} else {
k2 = Object.keys(green).find(k => green[k].indexOf(data2) >= 0);
index2 = green[k2].indexOf(data2);
green[k2].splice(index2, 1);
}
}
}
random[key3].push(data2);
$(this).detach();
var element2 = $(this).detach();
$('#randomid').prepend('<div class="pilldiv randompill class" >' + element2.html() + '</div>');
});
}
redraw();
listener();
var testing = JSON.stringify(green);
.pilldiv {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
color: Black;
margin: 2px;
}
.randompill:after{
content: "\002B";
float: left;
width:16px;
}
.new-green-fruit:after{
content: "\292B";
float: left;
width:16px;
}
.redpill {
background-color: Pink;
cursor:default;
}
.greenpill {
background-color: SpringGreen;
cursor:default;
}
.randompill {
background-color: LightBlue;
cursor:pointer;
}
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center;
}
.wrappingflexbox {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.top {
margin-bottom: 20px
}
h3{
font-weight: normal;
}
.panel {
display: table;
height: 100%;
width: 60%;
background-color:white;
border: 1px solid black;
margin-left: auto;
margin-right: auto;
}
.new-green-fruit{
background-color: LightBlue;
cursor:pointer;
}
.top{
margin-bottom:30px;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div class="panel">
<div style="float:left;width:calc(50% - 5px);">
<h3 class="class center">Total Fruits</h3>
<div id="combineid" class="combineclass wrappingflexbox top"></div>
</div>
<div style="float:right;width:calc(50% - 5px)">
<h3 class="class center">Random Fruits</h3>
<div id="randomid" class="randomclass wrappingflexbox top"></div>
</div>
</div>
</body>
</html>

It is working fine as expected. Look into the code base properly may be you are missing something.
var greenFruits = ["Watermelon", "Durian", "Avacado", "Lime", "Honeydew"];
console.log("Green Fruits Object : ", greenFruits);
console.log("Green Fruits String : ", JSON.stringify(greenFruits));
greenFruits.push("Guava");
console.log("Green Fruits Object : ", greenFruits);
console.log("Green Fruits String : ", JSON.stringify(greenFruits));

Related

Adding backgroundImage to body in jquery in second loop not working

I have three classes box with randomly selected image and from array items, there is a square box002 at right lower portion, this can be drag and droppped to any of three box if it find match the box will dissappear . likwise three box will dissappear.
then a class bodyblue is added to body with backgroundImage named middle bg is added to body for 10 seconds . after again 3 box appear for drag and drop.
in the second level after this three boxes are dragged&dropped and deleted, when bodyblue is added to body the backgroundImage middle bg is not appearing in for 10 seconds.
How to add bodyblue backgroundImage to body using jquery in second level and third level?
var array2 = [];
var arraycart = [];
var disparray = [];
var bg = [];
var dataURL;
var timeOut;
counter = 0;
var items = [{
label: '1',url: 'https://via.placeholder.com/150x150.jpg?text=image1'},
{label: '2',url:'https://via.placeholder.com/150x150.jpg?text=image2'},
{label: '3',url:'https://via.placeholder.com/150x150.jpg?text=image3'},
{label: '4',url:'https://via.placeholder.com/150x150.jpg?text=image4'},
{label: '5',url:'https://via.placeholder.com/150x150.jpg?text=image5'},
{label: '6',url:'https://via.placeholder.com/150x150.jpg?text=image6'},
{label: '7',url:'https://via.placeholder.com/150x150.jpg?text=image7'},
{label: '8',url:'https://via.placeholder.com/150x150.jpg?text=image8'},
{label: '9',url:'https://via.placeholder.com/150x150.jpg?text=image9'},
{label:'10',url:'https://via.placeholder.com/150x150.jpg?text=image10'}
];
var notes = ['https://via.placeholder.com/150x150.jpg?text=image1',
'https://via.placeholder.com/150x150.jpg?text=image2',
'https://via.placeholder.com/150x150.jpg?text=image3',
'https://via.placeholder.com/150x150.jpg?text=image4',
'https://via.placeholder.com/150x150.jpg?text=image5',
'https://via.placeholder.com/150x150.jpg?text=image6',
'https://via.placeholder.com/150x150.jpg?text=image7',
'https://via.placeholder.com/150x150.jpg?text=image8',
'https://via.placeholder.com/150x150.jpg?text=image9',
'https://via.placeholder.com/150x150.jpg?text=image10'
];
var tempimages = [];
var notesselected = [];
array2 = items.slice();
var item;
//----------------------------------------------change backgroundImage----------------------------------------------------------
function changemainbackground() {
debugger;
var c = document.getElementById('main');
var img = document.getElementById('main'),
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
// Display the url to the user
//console.log('Image URL: ' + bi);
bodycontents = document.getElementById('main');
if (counter >= 0) {
bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
d = bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
//console.log(d);
}
counter++;
//console.log("counter is"+counter);
//console.log(bodycontents);
//console.log(d);
}
//--------------------------^^^^^change backgroundImage end here^^^^^^^--------------------------------------------------------
//----------------------------------------------hiddenImage------------------------------------------------------------------------
hiddenimgnumber = 0;
var images = ['https://picsum.photos/200/300', 'https://picsum.photos/200/300', 'https://picsum.photos/200/300'];
//var bg=['https://via.placeholder.com/150x150.jpg?text=image1','https://via.placeholder.com/150x150.jpg?text=image2'];
var bg = ['https://picsum.photos/200/300?image=2', 'https://picsum.photos/200/300?image=3', 'https://picsum.photos/200/300?image=4'];
var refreshIntervalId = setInterval(function() {
image = document.getElementById('hiddenimageid');
image.src = images[hiddenimgnumber];
}, 1)
function hiddenimage() {
clearInterval(refreshIntervalId);
image = document.getElementById('hiddenimageid');
image.src = images[hiddenimgnumber];
//console.log(hiddenimgnumber);
hiddenimgnumber++;
}
//-------------------------------------------------^^^hidden Image ends^^^------------------------------------------------------
window.onload = function() {}
function rvalue() {
elements = document.getElementsByClassName("box");
for (var i = 0; i < elements.length; i++) {
//debugger;
elements[i].style.border = "2px solid #c57232 ";
elements[i].style.borderBottom = "5px solid #c57232 ";
//object.style.borderRadius = "1-4 length|% / 1-4 length|%|initial|inherit"
}
ptags = document.querySelectorAll('[name="values"]');
boxtags = document.getElementsByClassName("box");
//if array length is 0 then we need to identify the game as completed
if (array2.length === 0) {
alert('Game completed');
return;
}
for (var index = 0; index < 3; index++) {
randomIndex = Math.floor(Math.random() * array2.length)
item = array2[randomIndex];
array2.splice(randomIndex, 1);
try {
//ptags[index].style.visibility = "visible";
//ptags[index].textContent = "RS."+item.label;
ptags[index].dataset.itemLabel = item.label;
//using label as an identity
tempimages.push({
data: item,
label: item.label
});
notesselected.push({
data: item.url,
label: item.label
});
boxtags[index].style.backgroundImage = 'url(' + item.url + ')';
} catch (err) {
// console.log('Exception');
}
}
var tlen = tempimages.length;
}
function displayAllImages() {
try {
if (tempimages.length == 0) {
rvalue();
}
if (tempimages.length === 0) {
image = document.getElementById('slide');
image.style.display = 'none';
return;
}
// getting random item from the available items
var arr2 = tempimages;
item = arr2[Math.floor(Math.random() * arr2.length)]
image = document.getElementById('slide');
//getting notes item
//console.log(item);
///////console.log(item.label);
var dataURL = notes.filter(a => a.indexOf("?text=" + item.label) > 0)[0];
//var dataURL =item.url;
//var dataURL = item.label;
console.log(dataURL);
image.src = dataURL;
image.dataset.itemLabel = item.label;
} catch (err) {
//console.log(err.message);
}
};
$(function() {
displayAllImages();
});
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
var x = document.getElementById("slide").dataset.itemLabel;
var y = ev.target.dataset.itemLabel;
//add improvisation box drag is valid
if (ev.target.tagName === "DIV") {
y = ev.target.children[0].dataset.itemLabel;
}
//console.log(x);
//console.log(y);
if (x == y) {
ev.currentTarget.style.backgroundColor = 'initial';
ev.currentTarget.style.backgroundImage = 'initial';
ev.currentTarget.style.border = 'initial';
var pParagraph = ev.currentTarget.firstElementChild;
pParagraph.style.visibility = "hidden";
item = this.item;
tempimages = tempimages.filter(a => a.label !== item.label);
if (tempimages.length == 0) {
rvalue();
hiddenimage();
animateCongrat();
}
displayAllImages();
} else {
}
}
//----------------------------->>>animate congarat starts here-------------------------------------------------------------
var timeOut;
function animateCongrat() {
//debugger;
$('.congrats').show();
clearTimeout(timeOut);
addBlueBody();
hideCongratAndBlueBody();
}
function addBlueBody() {
$("html").css("background-color", " #070755 ");
$('body').addClass('bodyblue')
//console.log(url);
$('#container').hide();
$('#2container').hide();
$('#3container').hide();
$('#2').hide();
$('.completed').hide();
}
function hideCongratAndBlueBody() {
timeOut = setTimeout(() => {
$('.congrats').hide();
$("html").css("background-color", "");
$('body').removeClass('bodyblue')
$('#container').show();
$('#2container').show();
$('#3container').show();
$('#2').show();
$('.completed').hide();
changemainbackground();
}, 10000);
}
//----------------------------->>>animate congarat ends here-------------------------------------------------------------
body {
overflow: hidden;
}
.dashed {
border: 2px dashed #999 !important;
}
.bodyblue {
background-image: url(https://via.placeholder.com/1000x600?text=Middle+bg);
height: 100vh;
width: 100vw;
}
ul {
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
}
.box {
width: calc(33.3% - 4px);
border-radius: 5px;
border: #000 border-color: #e6e600;
margin: -2px;
background-color: #99ffff;
height: 16vh;
display: inline-flex;
align-items: center;
justify-content: center;
background-repeat: no-repeat;
background-size: cover;
cursor: pointer;
}
.box002 {
position: absolute;
top: 40.3vh;
left: 50.98vw;
cursor: pointer;
border: 2px solid black;
}
.box002 img {
width: 15.0vw;
height: 15.0vh;
border-radius: 0%;
}
#container {
white-space: nowrap;
border: px solid #CC0000;
}
.containerr {
border: px solid #FF3399;
}
.pic {
background-size: 100% 100%;
}
.container2 {
width: 29.0vw;
position: fixed;
top: 23.9vh;
left: 19.2vw;
}
body {
background-image: url(https://picsum.photos/200/300?image=0);
background-size: 100vw 100vh;
}
.reset img:hover {
opacity: 1
}
.hiddenimage {
position: absolute;
top: 4.3vh;
left: 50vw;
cursor: pointer;
}
.hiddenimage img {
width: 10.3vw;
height: 10.5vh;
border-radius: 15%;
}
.hand {
position: absolute;
top: 45.3vh;
left: 17vw;
cursor: pointer;
}
.hand img {
width: 25.3vw;
height: 25.5vh;
border-radius: 0%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container2">
<div class="containerr">
<div class="pic" id="content">
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10" style="">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
</div>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" border="rounded" />
</div>
<div class="congrats">
<div class="hiddenimage" style="display:none;">
<img src="" id="hiddenimageid" />
</div>
</div>

Jquery Fade Cycle through paragraphs and display one item at a time

I cannot get it to just display one at a time. It has to do a full cycle before it displays just one paragraph. Pulling my hair out.
$(function(){
setInterval(function(){$('.forumFeed > :first-child').fadeOut(3000).next('p').delay(3000).fadeIn(1000).end().appendTo('.forumFeed');}, 5000);
});
https://codepen.io/capseaslug/pen/yqyBXB
Hide all but the first paragraph tag by default. Inside the setInterval hide the one that is showing and display the next one (controlled by an index variable).
To make the items fade in/out nicely you can fade in the next element after the visible one is finished hiding.
Added some variables at the top to play with the aesthetics / number of items looped through.
SO didn't have moment.js so I hard coded some string. Codepen for a working version.
var numberOfItems = 10;
var flipSpeed = 2000;
var fadeOutSpeed = 500;
var fadeInSpeed = 200;
(function(c){
var uniquename = 'rssfeed' // id of target div
var query = 'select * from rss(0,' + numberOfItems + ') where url = "https://forums.mankindreborn.com/f/-/index.rss"'; // RSS Target, 0,5 signifies number of entries to show
var numretries = 1; // increase this number (number of retries) if you're still having problems
//////// No Need To Edit Beyond Here Unless You Want To /////////
var counter = typeof c === 'number'? c : numretries;
var thisf = arguments.callee;
var head = document.getElementsByTagName('head')[0];
var s = document.createElement('script');
window["callback_" + uniquename + (--counter)] = function(r){
head.removeChild(s);
if(r && r.query && r.query.count === 0 && counter > 0){
return thisf(counter);
}
//r now contains the result of the YQL Query as a JSON
var feedmarkup = '';
var feed = r.query.results.item // get feed as array of entries
for (var i=0; i<feed.length; i++) {
feedmarkup += '<p><span class="firstrowwrap"><a href="' + feed[i].link + '">';
feedmarkup += feed[i].title + '</a> <span class="comments"> Replies: ';
feedmarkup += feed[i].comments + ' </span></span><span class="secondRow"> <i class="fas fa-feather-alt"></i> ' ;
feedmarkup += feed[i].creator + ' <span class="posttime"> Last Post: ';
//pubishdate since
publishDate = feed[i].pubDate;
var inDate = publishDate;
var publisheddate = new Date(inDate);
feedmarkup += 'moment.js is missing ' + '</span></span></p>';
//endpublishdate since
}
document.getElementById(uniquename).innerHTML = feedmarkup;
};
var baseurl = "https://query.yahooapis.com/v1/public/yql?q=";
s.src = baseurl + encodeURIComponent(query) + "&format=json&callback=callback_" + uniquename + counter;
head.append(s);
})();
$(function(){
var index = 0;
setInterval(function() {
$('#rssfeed>p:visible').fadeOut(fadeOutSpeed, ()=> {
$('#rssfeed>p').eq(index).fadeIn(fadeInSpeed);
});
index++;
if(index === $('#rssfeed>p').length){
index = 0;
}
}, flipSpeed);
});
#main-container {
padding:4em;
background: #333;
font-family: 'exo'
}
#rssfeed p:not(:first-child) {
display: none;
}
a{
font-weight:
500;
color: #68ddda;
}
a:hover{
color: #4ca7a4;
}
.firstrowwrap{
display: flex;
justify-content: space-between;
}
.secondRow{
display: block;
padding-top: 4px;
margin-bottom: -5px;
}
#rssfeed p{
background-color: #212121;
padding: 10px;
width: 400px;
margin-bottom: 2px;
color: #464646;
}
.comments{
height: 18px;
position: relative;
z-index: 1;
padding-left: 8px;
margin-left: 4px;
font-size: 12px;
}
.comments:after{
content: "";
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 0px;
background-color: #969696;
border-radius: 2px;
z-index: -1;
margin-left: 4px;
}
.posttime{
float: right;
font-size: 13px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid" id="main-container">
<div class="row">
<div class="col-md-12">
<div class="forumFeed" id="rssfeed"></div>
</div>
</div>
</div>

Getting back same row format

I have this code below that allows me to move the value from Green Fruits Table to Suggested Fruits Table and vice versa but the problem is that after I move all the value from Suggested Fruits Table to Green Fruit Table all the value comes back as a single column and i want it to follow the original format which is 3 cells in a row. Is there any easy way to accomplish this? Any help would be greatly appreciated.
var obj = {};
var obj2 = {};
var obj3 = {};
var key = "Red Fruits";
obj[key] = ['Apple', 'Cherry', 'Strawberry', 'Cranberry', 'Tomato'];
var myArray = [];
myArray.push(obj);
var key2 = "Green Fruits";
obj3[key2] = ['Watermelon', 'Durian', 'Avacado', 'Kiwi', 'HoneyDew'];
var myArray2 = [];
myArray2.push(obj3);
var key3 = "Random Fruits";
obj2[key3] = ['Pomegranate', 'Honeydew', 'Plum', 'Mango', 'Lime', 'Pineapple', 'Starfruit', 'Cantaloupe', 'Blueberry'];
var myArray3 = [];
myArray3.push(obj2);
function redraw(obj3) {
var bodyString = '<tr>';
var headString = '';
$.each(obj[key], function(index) {
if (index % 3 == 0 && index > 0) {
bodyString += ('</tr><tr>');
}
bodyString += ('<td>' + obj[key][index] + '</td>');
});
bodyString += '</tr>';
headString += ('<tr><th colspan="' + obj[key].length + '">' + 'Red Fruits' + '</th></tr>');
$('.redclass tbody').html(bodyString);
$('.redclass thead').html(headString);
var bodyString2 = '<tr>';
var headString2 = '';
$.each(obj3[key2], function(index) {
if (index % 3 == 0 && index > 0) {
bodyString2 += ('</tr><tr>');
}
bodyString2 += ('<td class = "greenpilltable">' + obj3[key2][index] + '</td>');
});
bodyString2 += '</tr>';
headString2 += ('<tr><th colspan="' + obj3[key2].length + '">' + 'Green Fruits' + '</th></tr>');
$('.greenclass tbody').html(bodyString2);
$('.greenclass thead').html(headString2);
var bodyString3 = '<tr>';
var headString3 = '';
$.each(obj2[key3], function(index) {
if (index % 6 == 0 && index > 0) {
bodyString3 += ('</tr><tr>');
}
bodyString3 += ('<td>' + obj2[key3][index] + '</td>');
});
bodyString3 += '</tr>';
headString3 += ('<tr><th colspan="' + obj2[key3].length + '">' + 'Suggested Fruits' + '</th></tr>');
$('.randomclass tbody').html(bodyString3);
$('.randomclass thead').html(headString3);
}
function redraw_after(obj3) {
var bodyString3 = '<tr>';
var headString3 = '';
$.each(obj2[key3], function(index) {
if (index % 5 == 0 && index > 0) {
bodyString3 += ('</tr><tr>');
}
bodyString3 += ('<td>' + obj2[key3][index] + '</td>');
});
bodyString3 += '</tr>';
headString3 += ('<tr><th colspan="' + obj2[key3].length + '">' + 'Suggested Fruits' + '</th></tr>');
$('.randomclass tbody').html(bodyString3);
$('.randomclass thead').html(headString3);
}
function listener(obj3) {
$(document).ready(function() {
$(document).on("click", "#randomid td", function() {
data = this.innerHTML;
k1 = Object.keys(obj2).find(k => obj2[k].indexOf(data) >= 0)
index = obj2[k1].indexOf(data);
obj2[k1].splice(index, 1);
obj3[key2].push(data);
var element = $(this).detach();
$('#greenid > tbody').append('<tr><td class="new-green-fruit">' + element.html() + '</td></tr>');
redraw_after();
});
});
$(document).ready(function() {
$('body').on('click', 'td.new-green-fruit', function() {
data2 = this.innerHTML;
k2 = Object.keys(obj3).find(k => obj3[k].indexOf(data2) >= 0)
index2 = obj3[k2].indexOf(data2);
obj3[k2].splice(index2, 1);
obj2[key3].push(data2);
$(this).parent().detach();
var element2 = $(this).detach();
$('#randomid > tbody').append('<td>' + element2.html() + '</td>');
redraw_after(obj3);
});
});
}
redraw(obj3);
listener(obj3);
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center
}
table.pillstable {
float: left;
width: 70%
table-row: fixed;
}
div {
margin-bottom: 50px;
}
.new-green-fruit {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
background-color: #2196f3;
color: white;
cursor: pointer;
}
table.pilltable td {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
background-color: #2196f3;
color: white;
cursor: pointer;
}
table.pilltable th {
font-weight: normal;
border: 0;
padding: 10px 0;
}
.greenpilltable {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
background-color: #4caf50;
color: white;
cursor: pointer;
}
table.greenheader th {
font-weight: normal;
border: 0;
padding: 10px 0;
}
table.redpilltable td {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
background-color: #ff9800;
color: white;
cursor: pointer;
}
table.redpilltable th {
font-weight: normal;
border: 0;
padding: 10px 0;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div class="center">
<table cellspacing="5" id="redid" cellspacing="5" class="redclass redpilltable class">
<thead></thead>
<tbody></tbody>
</table>
<table cellspacing="5" id="greenid" cellspacing="5" class="greenclass greenheader class">
<thead></thead>
<tbody></tbody>
</table>
</div>
<div class="center">
<table cellspacing="5" id="randomid" cellspacing="5" class="randomclass pilltable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>

Getting back same number of rows

I have this code below that allows me to move the value from Green Fruits Table to Random Fruits Table and vice versa but the problem is that after I move all the value from Green Fruits Table back to Random Fruit Table all the value comes back as a single row but I want it to return the value like how it was originally. Is there any simple way to fix this Any suggestion would be greatly appreciated?
var obj = {};
var obj2 = {};
var key = "Red Fruits";
obj[key] = ['Apple', 'Cherry', 'Strawberry'];
var myArray = [];
myArray.push(obj);
var key2 = "Green Fruits";
obj[key2] = ['Watermelon', 'Durian', 'Avacado'];
var myArray2 = [];
myArray2.push(obj);
var key3 = "Random Fruits";
obj2[key3] = ['Kiwi', 'Pomegranate', 'Honeydew', 'Plum', 'Mango', 'Lime', 'Pineapple', 'Starfruit', 'Cantaloupe', 'Blueberry'];
var myArray3 = [];
myArray3.push(obj2);
function redraw(obj) {
var $header = $("<tr>"),
cols = 0,
bodyString = "";
$.each(obj, function(key, values) {
cols = Math.max(cols, values.length);
$header.append($('<th/>').text(key));
});
for (var i = 0; i < cols; i++) {
bodyString += '<tr>';
$.each(obj, function(key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : "") +
'</td>';
});
bodyString += '</tr>';
}
$('.fruitsclass thead').html($header);
$('.fruitsclass tbody').html(bodyString);
var bodyString = '<tr>';
var headString = '';
$.each(obj2[key3], function(index) {
if (index % 5 == 0 && index > 0) {
bodyString += ('</tr><tr>');
}
bodyString += ('<td>' + obj2[key3][index] + '</td>');
});
bodyString += '</tr>';
headString += ('<tr><th colspan="' + obj2[key3].length + '">' + 'Suggested Fruits' + '</th></tr>');
$('.carsclass tbody').html(bodyString);
$('.carsclass thead').html(headString);
}
function listener(obj) {
$(document).ready(function() {
$(document).on("click", "#carsid td", function() {
data = this.innerHTML;
k1 = Object.keys(obj2).find(k => obj2[k].indexOf(data) >= 0)
index = obj2[k1].indexOf(data);
obj2[k1].splice(index, 1);
obj[key2].push(data);
var element = $(this).detach();
$('#fruitsid > tbody').append('<tr><td></td><td class="new-green-fruit">' + element.html() + '</td></tr>');
});
});
$(document).ready(function() {
$('body').on('click', 'td.new-green-fruit', function() {
data2 = this.innerHTML;
k2 = Object.keys(obj).find(k => obj[k].indexOf(data2) >= 0)
index2 = obj[k2].indexOf(data2);
obj[k2].splice(index2, 1);
obj2[key3].push(data2);
$(this).parent().detach();
var element2 = $(this).detach();
$('#carsid > tbody').append('<td>' + element2.html() + '</td>');
});
});
}
redraw(obj);
listener(obj);
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center
}
table.skillsTable th {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
color: #0080ff;
font-weight: normal;
border-bottom: 1px solid #AAA5A4;
padding-bottom: 5px;
}
table.skillsTable {
float: left;
border-collapse: collapse;
width: 70%
}
table.pillstable {
float: left;
width: 70% table-row:fixed;
}
table.skillsTable td {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
padding-top: 8px;
padding-left: 11px;
font-size: 15px;
}
div {
margin-bottom: 50px;
}
.new-green-fruit {
color: lime;
}
table.pilltable td {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
background-color: #2196f3;
color: white;
}
table.pilltable th {
font-weight: normal;
border: 0;
padding: 10px 0;
}
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div id="result"> </div>
<div class="center">
<table id="fruitsid" class="fruitsclass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
<div class="center">
<table cellspacing="5" id="carsid" cellspacing="5" class="carsclass pilltable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
To fix this, I am adding some data properties in your random fruits, which I'm later using to get the right row and column to insert at. Have added some comments in code below to navigate.
Probably not the best implementation, but something like this should help you. (See snippet).
var obj = {}
var obj2 = {}
var key = 'Red Fruits'
obj[key] = ['Apple', 'Cherry', 'Strawberry']
var myArray = []
myArray.push(obj)
var key2 = 'Green Fruits'
obj[key2] = ['Watermelon', 'Durian', 'Avacado']
var myArray2 = []
myArray2.push(obj)
var key3 = 'Random Fruits'
obj2[key3] = ['Kiwi', 'Pomegranate', 'Honeydew', 'Plum', 'Mango', 'Lime', 'Pineapple', 'Starfruit', 'Cantaloupe', 'Blueberry']
var myArray3 = []
myArray3.push(obj2)
function redraw (obj) {
var $header = $('<tr>'),
cols = 0,
bodyString = ''
$.each(obj, function (key, values) {
cols = Math.max(cols, values.length)
$header.append($('<th/>').text(key))
})
for (var i = 0; i < cols; i++) {
bodyString += '<tr>'
$.each(obj, function (key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : '') +
'</td>'
})
bodyString += '</tr>'
}
$('.fruitsclass thead').html($header)
$('.fruitsclass tbody').html(bodyString)
var bodyString = '<tr>'
var headString = ''
$.each(obj2[key3], function (index) {
if (index % 5 == 0 && index > 0) {
bodyString += ('</tr><tr>')
}
// adding data row and data column attributes
bodyString += ('<td data-row="' + parseInt(index / 5) + '" data-column="' + index % 5 + '">' + obj2[key3][index] + '</td>')
})
bodyString += '</tr>'
headString += ('<tr><th colspan="' + obj2[key3].length + '">' + 'Suggested Fruits' + '</th></tr>')
$('.carsclass tbody').html(bodyString)
$('.carsclass thead').html(headString)
}
function listener (obj) {
$(document).ready(function () {
$(document).on('click', '#carsid td', function () {
data = this.innerHTML
k1 = Object.keys(obj2).find(k => obj2[k].indexOf(data) >= 0)
index = obj2[k1].indexOf(data)
obj2[k1].splice(index, 1)
obj[key2].push(data)
var element = $(this).clone() // cloning to keep the placeholder in random fruits
$(this).replaceWith('<td></td>') // and removing it's content.
element.addClass('new-green-fruit')
// using outerHTML to get the whole attributes of the fruit including row and col
$('#fruitsid > tbody').append('<tr><td></td>' + element[0].outerHTML + '</tr>')
})
})
$(document).ready(function () {
$('body').on('click', 'td.new-green-fruit', function () {
data2 = this.innerHTML
k2 = Object.keys(obj).find(k => obj[k].indexOf(data2) >= 0)
index2 = obj[k2].indexOf(data2)
obj[k2].splice(index2, 1)
obj2[key3].push(data2)
$(this).parent().detach()
var element2 = $(this).detach()
var row = element2.data('row')
var col = element2.data('column')
// inserting in right row and column gathered from above.
$($($('#carsid > tbody tr')[row]).find('td')[col]).replaceWith(element2)
return false;
})
})
}
redraw(obj)
listener(obj)
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center
}
table.skillsTable th {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
color: #0080ff;
font-weight: normal;
border-bottom: 1px solid #AAA5A4;
padding-bottom: 5px;
}
table.skillsTable {
float: left;
border-collapse: collapse;
width: 70%
}
table.pillstable {
float: left;
width: 70% table-row:fixed;
}
table.skillsTable td {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
padding-top: 8px;
padding-left: 11px;
font-size: 15px;
}
div {
margin-bottom: 50px;
}
.new-green-fruit {
color: lime;
}
table.pilltable td {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
background-color: #2196f3;
color: white;
}
table.pilltable th {
font-weight: normal;
border: 0;
padding: 10px 0;
}
<body>
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="//#" />
</head>
<body>
<div id="result"> </div>
<div class="center">
<table id="fruitsid" class="fruitsclass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
<div class="center">
<table cellspacing="5" id="carsid" cellspacing="5" class="carsclass pilltable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
To do this, I've created a new function redraw_after(obj) by slightly modifying your redraw(obj) function and placing both of the functions in the script. Now, just call the new redraw_after(obj) function after each of the listener functions to get the desired output.
What is happening here is that after each click, all the objects are redrawn to that 5 column in each row style. That's why it is working. Though, the new elements are added at the last of the queue each time, I guess the implementation is perfect, however.
var obj = {};
var obj2 = {};
var key = "Red Fruits";
obj[key] = ['Apple', 'Cherry', 'Strawberry'];
var myArray = [];
myArray.push(obj);
var key2 = "Green Fruits";
obj[key2] = ['Watermelon', 'Durian', 'Avacado'];
var myArray2 = [];
myArray2.push(obj);
var key3 = "Random Fruits";
obj2[key3] = ['Kiwi', 'Pomegranate', 'Honeydew', 'Plum', 'Mango', 'Lime', 'Pineapple', 'Starfruit', 'Cantaloupe', 'Blueberry'];
var myArray3 = [];
myArray3.push(obj2);
function redraw(obj) {
var $header = $("<tr>"),
cols = 0,
bodyString = "";
$.each(obj, function(key, values) {
cols = Math.max(cols, values.length);
$header.append($('<th/>').text(key));
});
for (var i = 0; i < cols; i++) {
bodyString += '<tr>';
$.each(obj, function(key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : "") +
'</td>';
});
bodyString += '</tr>';
}
$('.fruitsclass thead').html($header);
$('.fruitsclass tbody').html(bodyString);
var bodyString = '<tr>';
var headString = '';
$.each(obj2[key3], function(index) {
if (index % 5 == 0 && index > 0) {
bodyString += ('</tr><tr>');
}
bodyString += ('<td>' + obj2[key3][index] + '</td>');
});
bodyString += '</tr>';
headString += ('<tr><th colspan="' + obj2[key3].length + '">' + 'Suggested Fruits' + '</th></tr>');
$('.carsclass tbody').html(bodyString);
$('.carsclass thead').html(headString);
}
function redraw_after(obj) {
var bodyString = "";
var bodyString = '<tr>';
var headString = '';
$.each(obj2[key3], function(index) {
if (index % 5 == 0 && index > 0) {
bodyString += ('</tr><tr>');
}
bodyString += ('<td>' + obj2[key3][index] + '</td>');
});
bodyString += '</tr>';
headString += ('<tr><th colspan="' + obj2[key3].length + '">' + 'Suggested Fruits' + '</th></tr>');
$('.carsclass tbody').html(bodyString);
$('.carsclass thead').html(headString);
}
function listener(obj) {
$(document).ready(function() {
$(document).on("click", "#carsid td", function() {
data = this.innerHTML;
k1 = Object.keys(obj2).find(k => obj2[k].indexOf(data) >= 0)
index = obj2[k1].indexOf(data);
obj2[k1].splice(index, 1);
obj[key2].push(data);
var element = $(this).detach();
$('#fruitsid > tbody').append('<tr><td></td><td class="new-green-fruit">' + element.html() + '</td></tr>');
redraw_after(obj);
});
});
$(document).ready(function() {
$('body').on('click', 'td.new-green-fruit', function() {
data2 = this.innerHTML;
k2 = Object.keys(obj).find(k => obj[k].indexOf(data2) >= 0)
index2 = obj[k2].indexOf(data2);
obj[k2].splice(index2, 1);
obj2[key3].push(data2);
$(this).parent().detach();
var element2 = $(this).detach();
$('#carsid > tbody').append('<td>' + element2.html() + '</td>');
redraw_after(obj);
});
});
}
redraw(obj);
listener(obj);
.class {
font-family: Open Sans;
}
.center {
display: flex;
justify-content: center
}
table.skillsTable th {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
color: #0080ff;
font-weight: normal;
border-bottom: 1px solid #AAA5A4;
padding-bottom: 5px;
}
table.skillsTable {
float: left;
border-collapse: collapse;
width: 70%
}
table.pillstable {
float: left;
width: 70% table-row:fixed;
}
table.skillsTable td {
border-left: 1px solid #AAA5A4;
border-right: 1px solid #AAA5A4;
padding-top: 8px;
padding-left: 11px;
font-size: 15px;
}
div {
margin-bottom: 50px;
}
.new-green-fruit {
color: lime;
}
table.pilltable td {
padding: 8px 15px;
text-align: center;
font-size: 15px;
border-radius: 25px;
background-color: #2196f3;
color: white;
}
table.pilltable th {
font-weight: normal;
border: 0;
padding: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"> </div>
<div class="center">
<table id="fruitsid" class="fruitsclass skillsTable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
<div class="center">
<table cellspacing="5" id="carsid" class="carsclass pilltable class">
<thead></thead>
<tbody></tbody>
</table>
</div>
That happens because you push the elements outside the rows and you don't save their positions. Solution: save the position and insert inside tr
function getPosition(data) {
return {
row: Number(data.split(' ')[0]),
column: Number(data.split(' ')[1])
};
}
Array.from(document.getElementsByClassName('elem')).forEach(elem => {
elem.addEventListener('click', e => {
if(e.target.parentNode.classList.contains('tr')) {
let position = getPosition(e.target.dataset.position);
let row = document.querySelector('.tab').querySelectorAll('tr')[position.row];
row.insertBefore(e.target, row.children[position.column]);
} else {
document.querySelector('.tr').appendChild(e.target);
}
});
});
.elems {
border: 1px solid black;
}
.elem {
background: rgb(0, 120, 255);
padding: 10px 10px;
border-radius: 10px;
}
<table class='elems'>
<tr class='tr'>
</tr>
</table>
<table class='tab'>
<tr><td class='elem' data-position='0 0'>ELem1</td>
<td class='elem' data-position='0 1'>Long ELem2</td>
<td class='elem' data-position='0 2'>Longer ELem3</td></tr>
<tr><td class='elem' data-position='1 0'>Even Longer ELem4</td>
<td class='elem' data-position='1 1'>Short ELem5</td>
<td class='elem' data-position='1 2'>Just ELem6</td></tr>
</table>
You could also use flexbox
Array.from(document.getElementsByClassName("elem")).forEach(elem => {
elem.addEventListener('click', e => {
document.querySelector('.flex-box').appendChild(e.target);
});
});
.flex-box {
display: flex;
width: 500px;
flex-wrap: wrap;
}
.elem {
background: rgb(0, 120, 255);
padding: 10px 10px;
border-radius: 10px;
}
.flex-box .elem {
flex: 1 0 content;
}
<div class='elems'>
<div class='elem'>ELem1</div>
<div class='elem'>Long ELem2</div>
<div class='elem'>Longer ELem3</div>
<div class='elem'>Even Longer ELem4</div>
<div class='elem'>Short ELem5</div>
<div class='elem'>Just ELem6</div>
</div>
<div class='flex-box'></div>
This solution requires more code because you have to move elements from table to div (possible to avoid with some changes to the table). Other than that, the elements are not automatically stretched when using flexbox, so you don't have to play with the elements to prevent overstretching when one of them has long contents.
If you want to preserve the order, use the order property.

javascript background image change using array

I am not exprienced javascript programmer so I try to play with javascript. I am trying to make a slideshow by clicking on a button. Function I am trying to make a function with array that holds the names of all the images and changing the background-image according to the index of the array. I did only this part of function yet and I cant get what is wrong.
function change(lol){
var img = ["veni1.jpg", "veni2.jpg", "veni3"];
var middle = document.getElementById("vvvmiddle");
var index = img.indexOf(middle.style.backgroundImage);
if(change === "right"){
var current = index + 1;
middle.style.backgroundImage = img[current];
}
}
middle {
width:1262px;
height:550px;
background-color: white;
margin-left: -7px;
}
#vvvmiddle {
width:700;
height:400;
background-image:url('veni1.jpg');
margin: 20px 0px 0px 310px;
float:left;
}
#sipka {
width:40;
height:40;
border-radius: 100px;
background-color: #DCDCDC;
float:right;
margin: 450px 410px 0px 0px;
}
#sipkatext {
font-family: Impact;
color: white;
font-size: 30px;
padding-left: 10px;
padding-top: 1px;
}
#sipkaurl {
text-decoration: none;
}
#sipka:hover {
background-color: #3399FF;
}
#sipka2:hover {
background-color: #3399FF;
}
#sipka2 {
width:40;
height:40;
border-radius: 100px;
background-color: #DCDCDC;
float:right;
margin: 450px -100px 0px 0px;
}
#sipkatext2 {
font-family: Impact;
color: white;
font-size: 30px;
padding-left: 13px;
padding-top: 1px;
}
<div id="middle">
<div id="vvvmiddle">
<div id="sipka" onclick="change('left')">
<div id="sipkatext">
<</div>
</div>
<div id="sipka2" onclick="change('right')">
<div id="sipkatext2">></div>
</div>
</div>
</div>
A possible solution may be this one:
var img = ["img1.png", "img2.png", "img3.png"];
var len = img.length;
var url = 'Some url...';
var current=0;
var middle = document.getElementById("vvvmiddle");
middle.style.backgroundImage = "url(" + url + img[current] + ")";
function change(dir){
if(dir == "right" && current < len-1){
current++;
middle.style.backgroundImage = "url(" + url + img[current] + ")";
} else if(dir == "left" && current > 0){
current--;
middle.style.backgroundImage = "url(" + url + img[current] + ")";
}
}
See it in action, check here jsfiddle.
You can try with that:
function change(lol) {
var img = ["veni1.jpg", "veni2.jpg", "veni3"];
var middle = document.getElementById("vvvmiddle");
var index = img.indexOf(middle.style.backgroundImage);
if(lol === "right"){
index = (index + 1) % img.length;
} else {
index = (index + img.length - 1) % img.length;
}
middle.style.backgroundImage = img[index];
}
You are checking wrong variable in condition, it should be lol, not change:
if(lol === "right"){
var current = index + 1;
middle.style.backgroundImage = img[current];
}
Also you should handle "last image" case like Nicolas suggests.

Categories

Resources