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));
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>
Alright so I have run into what I believe is an optimization issue. I have written a short app that grabs data from two fields, rips them apart character by character and matches them to each other, highlighting discrepancies. The issue seems to be that because the function loops through and not only prints each character one at a time, but changes color in a new span one at a time, there is a severe amount of bottlenecking for large data entries. One sentence of even five work just fine, but when you get up to a full page of text, things bog down and in some cases crash. I have tried to look up some fixes for repaints/reflows, but I haven't run into this issue before and don't know much about it. ANy tips welcome.
Code is here:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Data Comparison</title>
</head>
<body>
<p><strong>Insert text into fields one and two and press 'Compare'. Matching data is green non-matching is red. </strong></p>
<div class="userField">
<h1>Input Field 1</h1>
<textarea id="textAreaOne" rows="30" cols="65"></textarea>
</div>
<div class="userField">
<h1>Input Field 2</h1>
<textarea id="textAreaTwo" rows="30" cols="65"></textarea>
</div>
<div id="submission">
<button onclick="compare(textAreaOne);">Compare</button>
</div>
<div id="divOne">
<h1 id="titleOne">Output Field 1</h1>
<p id="outputOne"></p>
</div>
<div id ="divTwo">
<h1 id="titleTwo">Output Field 2</h1>
<p id="outputTwo"></p>
</div>
</body>
</html>
CSS:
body {
width: 100%;
margin: 0;
padding: 0;
font-family: Verdana, Geneva, sans-serif;
font-size: 15px;
}
.userField {
display: inline-block;
width: 44%;
margin: 15px;
padding: 15px;
background-color: lightgrey;
border-radius: 13px;
box-shadow: 3px 3px 3px slategrey;
}
#submission {
text-align: center;
}
#divOne {
display: inline-block;
margin: 15px;
padding: 15px;
width: 44%;
word-wrap: break-word;
background-color: lightgrey;
}
#divTwo {
display: inline-block;
background-color: lightgrey;
width: 44%;
word-wrap: break-word;
margin: 15px;
padding: 15px;
}
#titleOne {
background-color: white;
width: 240px;
border-radius: 30px;
padding: 6px;
}
#titleTwo {
background-color: white;
width: 240px;
border-radius: 30px;
padding: 6px;
}
JS:
const fieldOne = document.querySelector("#textAreaOne");
const fieldTwo = document.querySelector("#textAreaTwo");
function compare(){
document.querySelector("#outputOne").innerHTML = "";
document.querySelector("#outputTwo").innerHTML = "";
document.querySelector("#divOne").style.visibility = "hidden";
document.querySelector("#divTwo").style.display = "hidden";
let dataOne = [];
let arrOne = fieldOne.value;
let temp = arrOne.split("");
dataOne.push(temp);
let dataTwo = [];
let arrTwo = fieldTwo.value;
let tempTwo = arrTwo.split("");
dataTwo.push(tempTwo);
if (fieldOne.value.length <= fieldTwo.value.length){
for (var i = 0; i<fieldOne.value.length; i++){
if (dataOne[0][i] === dataTwo[0][i]){
document.querySelector("#outputOne").innerHTML += "<span style='color:green'>" + dataOne[0][i] + "</span>";
document.querySelector("#outputTwo").innerHTML += "<span style='color:green'>" + dataTwo[0][i] + "</span>";
} else {
document.querySelector("#outputOne").innerHTML += "<span style='color:red'>" + dataOne[0][i] + "</span>";
document.querySelector("#outputTwo").innerHTML += "<span style='color:red'>" + dataTwo[0][i] + "</span>";
}
}
if (fieldOne.value.length < fieldTwo.value.length){document.querySelector("#outputTwo").innerHTML += "<span>...</span>";}
}
else {
for (var i = 0; i<fieldTwo.value.length; i++){
if (dataOne[0][i] === dataTwo[0][i]){
document.querySelector("#outputOne").innerHTML += "<span style='color:green'>" + dataOne[0][i] + "</span>";
document.querySelector("#outputTwo").innerHTML += "<span style='color:green'>" + dataTwo[0][i] + "</span>";
} else {
document.querySelector("#outputOne").innerHTML += "<span style='color:red'>" + dataOne[0][i] + "</span>";
document.querySelector("#outputTwo").innerHTML += "<span style='color:red'>" + dataTwo[0][i] + "</span>";
}
}
if (fieldTwo.value.length < fieldOne.value.length){ document.querySelector("#outputOne").innerHTML += "<span>...</span>";}
}
document.querySelector("#divOne").style.visibility = "visible";
document.querySelector("#divTwo").style.visibility = "visible";
}
https://codepen.io/Axfinger/pen/QxvbqM?editors=0010
Thanks
The main reason your code is slow it's because you keep modify innerHtml for every letter.
This approach is way faster even with several paragraph:
[...]
let outOne = '';
let outTwo = '';
if (fieldOne.value.length <= fieldTwo.value.length){
for (var i = 0; i<fieldOne.value.length; i++){
if (dataOne[0][i] === dataTwo[0][i]){
outOne += dataOne[0][i];
outTwo += dataTwo[0][i];
} else {
outOne += "<span style='color:red'>" + dataOne[0][i] + "</span>";
outTwo += "<span style='color:red'>" + dataTwo[0][i] + "</span>";
}
}
if (fieldOne.value.length < fieldTwo.value.length){outTwo += "...";}
}
[...]
outputOne.innerHTML = outOne;
outputTwo.innerHTML = outTwo;
Note that I omitted parts of the code for clearness.
That said if you still need more speed:
Lookup for fitting as much data as possible into the red spans. That is the whole consecutive subsequence of different letters.
Execute the function in a webworker (Will take similar time but at least won't freeze the browser).
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.
for (i = 0; i < arrayData.length; i++) {
$(".swipe-wrap").append("<div class=\"final\">Hello!</div>");
console.log('hello');
}
This is what I currently have. My arrayData is an array that changes each load.
How can I get it so my class final each for loop will have an counter like such : <div class="final_1">Hello!</div> , <div class="final_2">Hello!</div>..
for (i = 0; i < arrayData.length; i++) {
$(".swipe-wrap").append("<div class=\"final_"+i+"\">Hello!</div>");
console.log('hello');
}
You should not perform DOM manipulation inside loops. Always perform bulk operation.
Try this:
var html = ""
for (i = 0; i < arrayData.length; i++) {
html += '<div class="final_'+i+'">Hello!</div>';
console.log('hello');
}
$(".swipe-wrap").append(html);
You can also use Array.forEach.
var html = ""
var arrayData = ["test1", "test2", "test3", "test4", "test5"];
console.log(arrayData);
arrayData.forEach(function(item, index) {
html += '<div class="tile final_' + index + '">Hello ' +item+ '!</div>';
console.log('hello');
});
$(".swipe-wrap").append(html);
.swipe-wrap {
background: #eee;
padding: 10px;
border: 1px solid gray;
}
.tile {
width: auto;
padding: 10px;
margin: 10px;
background: #fff;
border: 1px solid #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="swipe-wrap"></div>