Why I have NaN on Node.js? - javascript

I'm making a bulletin board now. Above is the template code for it, where page function has NaN. What is the reason for this error, and how should I fix it?
The code below is written in node.js.
module.exports = {
HTML:function(title, board, control, page){
return `
<!DOCTYPE html>
<html>
<head>
<title>${title}</title>
<meta charset="utf-8">
<style type="text/css">
ul.board, ol.board {
list-style: none;
margin: 0px;
padding: 5px;
}
form {
display: inline;
}
table.type09 {
border-collapse: separate;
text-align: left;
line-height: 2;
}
table.type09 thead th {
padding: 10px;
font-weight: bold;
vertical-align: top;
color: #369;
border-bottom: 3px solid #003699;
}
table.type09 tbody th {
width: 150px;
padding: 10px;
font-weight: bold;
vertical-align: top;
border-bottom: 1px solid #ccc;
background: #f3f6f7;
}
table.type09 td {
width: 350px;
padding: 10px;
vertical-align: top;
border-bottom: 1px solid #ccc;
}
</style>
</head>
<body>
<div id="board">
<table class="type09">
<thead>
<tr>
<th>제목</th>
<th>작성자</th>
<th>날짜</th>
<th>조회수</th>
</tr>
</thead>
<tbody>
${board}
</tbody>
</table>
${control}
</div>
${page}
</body>
</html>`;
},board: function (lifeboards) {
var board = ``;
for (i = 0; i < lifeboards.length; i++) {
var article = lifeboards[i];
var titleBold = article.titleBold;
board += `<tr>`;
if(titleBold == "1") {
board += `<td> <b><공지>${article.title}</b> </td>`;
board += `<td>${article.writer}</td>`;
board += `<td>${article.day}</td>`;
board += `<td>${article.see}</td>`;
board += `</tr>`;
}
}
for (i = 0; i < lifeboards.length; i++) {
var article = lifeboards[i];
var titleBold = article.titleBold;
board += `<tr>`;
if(titleBold == "1") {
board += `<td> ${i+1}. <b>${article.title}</b> </td>`;
} else if(titleBold == "0") {
board += `<td>${i+1}. ${article.title}</td>`;
}
board += `<td>${article.writer}</td>`;
board += `<td>${article.day}</td>`;
board += `<td>${article.see}</td>`;
board += `</tr>`;
}
return board;
},page:function (lifeboards) {
var page = ``;
page =+ `<tr>`;
page =+ `<td colspan="5">`;
for(j = 0; j < lifeboards.length/5; j++) {
page =+ `[${j+1}]`;
}
page =+ `</td>`;
page =+ `</tr>`;
return page;
}
}
The picture below shows how it works.
I don't know how much more detail Stackoverflow wants, but this is all my code and there's nothing more to explain.

Please use this one , you need to add concat ( + ) operator first then =. e.g. +=
page: function (lifeboards) {
var page = ``;
page += `<tr>`;
page += `<td colspan="5">`;
for (j = 0; j < lifeboards.length / 5; j++) {
page += `[${j + 1}]`;
}
page += `</td>`;
page += `</tr>`;
return page;
}
Hope this will solve the issue.

Related

Javascript to Add the specific cells and display it in the specific cell as well

Hi What I'm trying to do is from Sc1pts to Sc10pts
here's the link of the Files https://mega.nz/folder/fkcTAaDT#eCaku5ukYsGlg8T8W6U-FA
it should display to the PTS the sum of it
and Jersey # should not be included and Name of players, Name of players should be string only and if
not string set to empty and and alert please enter a name. I've been trying to do this almost three hours still not getting it.
var add = [];
var sum = 0;
var addNum = [];
function addPlayer() {
var table = document.getElementById("table");
var cells = table.querySelectorAll("td");
var row = table.insertRow();
var count = [];
for (i = 0; i < 13; i++) {
cells = row.insertCell(i);
// optional - make the tabel cells editable
//cells.setAttribute('contenteditable', true);
if (i > 1) {
cells = cells.innerHTML = "0";
}
}
addEvents(row);
}
function addPlayer1() {
var table = document.getElementById("table1");
var row = table.insertRow();
for (i = 0; i < 13; i++) {
cells = row.insertCell(i);
// optional - make the tabel cells editable
//cells.setAttribute('contenteditable', true);
if (i > 1) {
cells = cells.innerHTML = "0";
}
}
addEvents(row);
}
function addEvents(row) {
let cells = row.cells;
for (i = 0; i < cells.length; i++) {
if (cells[i] != cells[12]) {
cells[i].onclick = function() {
if (this.hasAttribute("data-clicked")) {
return;
}
this.setAttribute("data-clicked", "yes");
this.setAttribute("data-text", this.innerHTML);
var input = document.createElement("input");
input.setAttribute("type", "text");
input.value = this.innerHTML;
input.style.width = this.offsetWidth - this.clientleft * 2 + "px";
input.style.height = this.offsetHeight - this.clientTop * 2 + "px";
input.style.border = "0px";
input.style.fontFamily = "inherit";
input.style.fontSize = "inherit";
input.style.textAlign = "inherit";
input.style.backgroundColor = "LightGoldenRodYellow";
input.onblur = function() {
var td = input.parentElement;
var orig_text = input.parentElement.getAttribute("data-text");
var current_text = this.value;
orig_text = parseInt(orig_text);
current_text = parseInt(current_text);
if (orig_text != current_text) {
if (isNaN(current_text)) {
alert("Please enter a number");
td.removeAttribute("data-clicked");
td.removeAttribute("data-text");
td.innerHTML = "";
td.style.cssText = "padding: 5px";
} else {
//there are changes in the table
// save our data to our database
td.removeAttribute("data-clicked");
td.removeAttribute("data-text");
td.innerHTML = current_text;
td.style.cssText = "padding: 5px";
if (orig_text < current_text || cells[i] != cells[1]) {
sum += current_text;
console.log(sum);
} else if (orig_text > current_text) {
current_text = orig_text - current_text;
sum -= current_text;
console.log(sum);
}
}
}
//console.log(orig_text + 'is changed to' + current_text);
else {
td.removeAttribute("data-clicked");
td.removeAttribute("data-text");
td.innerHTML = orig_text;
td.style.cssText = "padding: 5px";
if (orig_text < current_text && cells[i] > cells[1]) {
sum += current_text;
console.log(sum);
} else if (orig_text > current_text && cells[i] > cells[1]) {
current_text = orig_text - current_text;
sum -= current_text;
console.log(sum);
}
}
//console.log("No changes made");
};
input.addEventListener("keypress", function(event) {
if (event.key == "Enter") {
this.blur();
}
});
this.innerHTML = "";
this.style.cssText = "padding: 0px 0px";
this.append(input);
this.firstElementChild.select();
};
}
}
}
* {
margin: 0;
padding: 0;
justify-content: center;
align-items: center;
text-align: center;
justify-items: center;
}
body {
font-family: sans-serif;
justify-content: center;
align-items: center;
text-align: center;
justify-items: center;
}
table,
thead,
tr,
th {
border: 1px solid black;
border-collapse: collapse;
padding: 5px;
}
table,
tbody,
tr,
td {
border: 1px solid black;
border-collapse: collapse;
padding: 5px;
}
table {
margin-left: auto;
margin-right: auto;
}
tr:nth-child(even) {
background-color: white;
}
th {
background-color: gray;
color: white;
}
button {
margin: 20px;
background-color: antiquewhite;
border: solid 1px black;
border-radius: 5px;
padding: 5px;
}
h1 {
margin: 2%;
}
.table-containers {
margin: 5%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=+, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<h1>Sports & Games Score Updates</h1>
<div class="table-containers">
<table id="table">
<thead>
<tr>
<th>Jersey #</th>
<th>Name of players</th>
<th>Sc1pts</th>
<th>Sc2pts</th>
<th>Sc3pts</th>
<th>Sc4pts</th>
<th>Sc5pts</th>
<th>Sc6pts</th>
<th>Sc7pts</th>
<th>Sc8pts</th>
<th>Sc9pts</th>
<th>Sc10pts</th>
<th>PTS</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<button type="button" onclick="addPlayer()">Add player</button>
</div>
<div class="table-containers">
<table id="table1">
<thead>
<tr>
<th>Jersey #</th>
<th>Name of players</th>
<th>Sc1pts</th>
<th>Sc2pts</th>
<th>Sc3pts</th>
<th>Sc4pts</th>
<th>Sc5pts</th>
<th>Sc6pts</th>
<th>Sc7pts</th>
<th>Sc8pts</th>
<th>Sc9pts</th>
<th>Sc10pts</th>
<th>PTS</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<button id="addTable" type="button" onclick="addPlayer1()">Add player</button>
</div>
<script src="index.js"></script>
</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 itareate over divs and create a new one if doesn't fits

Hello guys I hope you can help me with JavaScript, I'm trying to itarate over some divs, the issue is that when I iterate sometimes a div never change to the other divs, it suppose to be infinite, I will recive thousands of different divs with different height and it should create an other div container in the case it does not fits but I can not achieve it work's, I'm using Vanilla JavaScript because I'm lerning JavaScript Regards.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.big_container{
height: 600px;
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items{
background-color: gray;
height: 50px;
}
.new_container{
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
float: left;
margin-left: 5px;
}
</style>
</head>
<body>
<div class="big_container">
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
<div class="items">5</div>
<div class="items">6</div>
<div class="items">7</div>
<div class="items">8</div>
<div class="items">9</div>
<div class="items">10</div>
<div class="items">11</div>
<div class="items">12</div>
<div class="items">13</div>
</div>
<div class="new_container">
</div>
</body>
<script>
number = 0
sum = 0
new_container = document.getElementsByClassName('new_container')[number].offsetHeight
divs = document.getElementsByClassName('items')
for ( var i = 0; i < divs.length; i++ ){
sum += this.document.getElementsByClassName( 'items' )[0].offsetHeight
if ( sum <= new_container ){
console.log(sum, "yes")
document.getElementsByClassName("new_container")[number].appendChild( this.document.getElementsByClassName( 'items' )[0] )
} else {
sum = 0
console.log(sum, "NO entra")
nuevo_contenedor = document.createElement('div'); // Creo un contenedor
nuevo_contenedor.className = "new_container";
nuevo_contenedor.setAttribute("style", "background-color: red;");
document.body.appendChild(nuevo_contenedor)
number += + 1
}
}
</script>
</html>
I really apreciate a hand.
I know that I'm late, but there is my approach how this can be done.
// generate items with different height
function generateItems(count) {
const arr = [];
for (let i = 0; i < count; i++) {
const div = document.createElement("DIV");
const height = Math.floor((Math.random() * 100) + 10);
div.setAttribute("style", `height: ${height}px`);
div.setAttribute("class", "items");
const t = document.createTextNode(i + 1);
div.appendChild(t);
arr.push(div);
}
return arr;
}
function createNewContainer(height) {
const new_container = document.createElement("DIV")
new_container.setAttribute("class", "new_container");
new_container.setAttribute("style", `height: ${height}px`)
document.body.appendChild(new_container);
return new_container;
}
function breakFrom(sourceContainerId, newContainerHeight) {
const srcContainer = document.getElementById(sourceContainerId);
const items = srcContainer.childNodes;
let new_container = createNewContainer(newContainerHeight);
let sumHeight = 0;
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (item.offsetHeight > newContainerHeight) {
// stop!!! this item too big to fill into new container
throw new Error("Item too big.");
}
if (sumHeight + item.offsetHeight < newContainerHeight) {
// add item to new container
sumHeight += item.offsetHeight;
new_container.appendChild(item.cloneNode(true));
} else {
// create new container
new_container = createNewContainer(newContainerHeight);
new_container.appendChild(item.cloneNode(true));
// don't forget to set sumHeight)
sumHeight = item.offsetHeight;
}
}
// if you want to remove items from big_container
// for (let i = items.length - 1; i >= 0; i--) {
// srcContainer.removeChild(items[i]);
// }
}
// create big container with divs
const big_container = document.getElementById("big_container");
const items = generateItems(13);
items.forEach((div, index) => {
big_container.appendChild(div);
});
breakFrom("big_container", 300);
#big_container {
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items {
background-color: gray;
border: 1px solid #000000;
text-align: center;
}
.new_container {
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
border: 1px solid red;
float: left;
margin-left: 5px;
}
<div id="big_container"></div>
This example gives you the ability to play with divs of random height. Hope, this will help you.

Javascript increment up within a loop

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>

Create a pyramid structure diagram on a page from the user input

I want to create a pyramid like structure on a page from the user input, and the structure should appear like this,
I tried to loop in JS to display the structure but can't change the css property in JS loop according to user input. Here is the code on this page :
var objContainer = document.getElementById("container"),
intLevels = 10,
strBlocksHTML = '';
for (var i = 0; i < intLevels; i++) {
strBlocksHTML += '<div class="buildingBlock"></div>';
strBlocksHTML += '<div></div>'; // Line break after each row
}
objContainer.innerHTML = strBlocksHTML;
.buildingBlock {
display: inline-block;
width: 20px;
height: 20px;
margin: 2px 5px;
background-color: #eee;
border: 2px solid #ccc;
}
#container {
text-align: center;
}
<div id="container"></div>
The output is displayed as a tower and also want to remove the spacing between each <div> element. How can I change this by using jquery or by some other method ? The above image is the desired output that I want.
By changing the first strBlocksHTML row to
strBlocksHTML += '<div class="buildingBlock" style="width: ' + Number(20 + 40 * i) + 'px"></div>';
it works.
you need to do some thing like this
for( var i=0; i<intLevels; i++ ){
var wd = 20 * i;
strBlocksHTML += '<div class="buildingBlock" style="width:'+wd+'px"></div>';
strBlocksHTML += '<div></div>'; // Line break after each row
}
var objContainer = document.getElementById("container"),
intLevels = 10,
strBlocksHTML = '';
for (var i = 0; i < intLevels; i++) {
var wd = 20 * i;
strBlocksHTML += '<div class="buildingBlock" style="width:' + wd + 'px;"></div>';
strBlocksHTML += '<div></div>'; // Line break after each row
}
objContainer.innerHTML = strBlocksHTML;
.buildingBlock {
display: inline-block;
width: 20px;
height: 20px;
margin: 2px 5px;
background-color: #eee;
border: 2px solid #ccc;
margin-top: -20px;
}
#container {
text-align: center;
}
<div id="container"></div>
you can allign these closer by using css
You could simple set the width via the style attribute on each created div, and calculate it dynamically – I’ve change your loop to run backwards, something like this:
for(var i=intLevels; i>0; --i) {
strBlocksHTML += '<div class="buildingBlock" style="width:'+(250-i*20)+'px"></div>';
}
Change the values (250px width from which i*20 gets subtracted) as you see fit, resp. calculate them dynamically based on the number of pyramid levels wanted.
And also you do not need the empty divs for line breaks – just keep your divs as display:block, and set the margin to auto to center them.
var objContainer = document.getElementById("container"),
intLevels = 10,
strBlocksHTML = '';
for (var i = intLevels; i > 0; --i) {
strBlocksHTML += '<div class="buildingBlock" style="width:' + (250 - i * 20) + 'px"></div>';
}
objContainer.innerHTML = strBlocksHTML;
.buildingBlock {
height: 20px;
margin: auto;
background-color: #eee;
border: 2px solid #ccc;
}
#container {
text-align: center;
}
<div id="container"></div>
var objContainer = document.getElementById("container"),
intLevels = 10,
strBlocksHTML = '';
for (var i = 0; i < intLevels; i++) {
strBlocksHTML += '<div class="buildingBlock" style="width:' + (10 * i) + 'px"></div>';
//strBlocksHTML += '<div></div>'; // Line break after each row
}
objContainer.innerHTML = strBlocksHTML;
.buildingBlock {
display: block;
width: 20px;
height: 20px;
margin: 0 auto;
background-color: #eee;
border: 2px solid #ccc;
}
#container {
text-align: center;
}
<div id="container"></div>

Categories

Resources