Javascript Dynamic Table with each cell having an onmouse event? - javascript

I've created a dynamic table using Javascript. Now what I'm trying to do is for each cell that is dynamically generated, there is an onmouseover event that would change that particular cell's backgroundColor.
The problem I have is that when I generate the table and try to have an onmouseover function with each dynamically generated cell the function only works for the last generated cell.
Here's a copy of my code. (Note: I have only tested this on Chrome)
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 5px;
text-align: center;
}
</style>
<script type="text/javascript">
var table;
function init(){
table = document.getElementById("mytable");
}
function makeCells(){
init();
for(var a=0;a<20;a++){
var row = table.insertRow(-1);
for(var b=0;b<20;b++){
cell = row.insertCell(-1);
cell.innerHTML = a*b;
cell.onmouseover = function(){cell.style.backgroundColor = "yellow";};
}
}
}
</script>
</head>
<body onload="javascript: makeCells();">
<table id="mytable"></table>
</body>
</html>
Any advice would be greatly appreciated.

Some Improvements. 3 things I would change:
Don't edit inline styles with javascript. Instead, add or remove a class. see # 3.
Don't do so many event handlers in your "onload", "onmouseover". Its better to add an event listener.
It is better performance to add all of the new elements at one time instead of individually. See this article: https://developers.google.com/speed/articles/reflow
Here is a way to optimize the Javascript:
HTML
<table id="table"></table>
CSS
body {
padding: 40px;
}
.yellow {
background: yellow;
}
td {
padding: 10px 20px;
outline: 1px solid black;
}
JavaScript
function propegateTable() {
var table = document.getElementById("table");
//will append rows to this fragment
var fragment = document.createDocumentFragment();
for(var a=0; a<10; a++){ //rows
//will append cells to this row
var row = document.createElement("tr");
for(var b=0;b<5;b++){ //collumns
var cell = document.createElement("td");
cell.textContent = a + ", " + b;
// event listener
cell.addEventListener("mouseover", turnYellow);
row.appendChild(cell);
}
fragment.appendChild(row);
}
//everything added to table at one time
table.appendChild(fragment);
}
function turnYellow(){
this.classList.add("yellow");
}
propegateTable();
http://codepen.io/ScavaJripter/pen/c3f2484c0268856d3c371c757535d1c3

I actually found the answer myself playing around with my code.
In the line:
cell.onmouseover = function(){cell.style.backgroundColor = "yellow";};
I changed it to:
cell.onmouseover = function(){this.style.backgroundColor = "yellow";};

Related

Save content editable HTML table in multiple fields

I need to develop a HTML table where one of the table column is editable on its row and the table row is dynamic in term of the row number.
I come across a problem where when I automate the saveEdits() function, the code is not working.
Here is my code, where the 'cnt' is a dynamic numeric number. Example cnt=50
<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
table ,tr td{
border:1px solid #dddddd;
padding: 8px;
}
tbody {
display:block;
height:600px;
overflow:auto;
}
thead, tbody tr {
display:table;
width:100%;
table-layout:fixed;
}
thead {
width: calc( 100% - 1em )
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
<script type="text/javascript">
function saveEdits(cnt) {
//get the editable elements.
var str_out = ''
while (cnt>0){
str1 = '\'edit' + cnt + '\': document.getElementById(\'edit' + cnt + '\').innerHTML,\n'
str_out = str_out.concat(' ', str1);
cnt--;
};
var editElems= { str_out };
alert(editElems)
//save the content to local storage. Stringify object as localstorage can only support string values
localStorage.setItem('userEdits', JSON.stringify(editElems));
}
function checkEdits(){
//find out if the user has previously saved edits
var userEdits = localStorage.getItem('userEdits');
alert(userEdits) // suppose to print {"edit1":" rpeyy7<br>","edit2":" tpruiiy<br>","edit3":" opty<br>"}
if(userEdits){
userEdits = JSON.parse(userEdits);
for(var elementId in userEdits){
document.getElementById(elementId).innerHTML = userEdits[elementId];
}
}
}
</script>
</head>
<body onload="checkEdits()">
<table id="myTable">
<thead>
<tr>
<td style="background-color:#A9A9A9" > Field#1 </td>
<td style="background-color:#A9A9A9" > Field#2 </td>
<td style="background-color:#A9A9A9" > Field#3- Each Row Under field#3 is content EditableByUser </td>
</tr>
</thead>
<tbody>
// Here is the python code that loop through a diectionary content
cnt = 0
for c in sorted(data_dict.keys()) :
cnt += 1
<tr>
<td> {0} </td> //Field#1
<td> {0} </td> //Field#2
...
...
<td id="edit{0}" contenteditable="true" onKeyUp="saveEdits({0});"> {1} </td>\n'.format(cnt,comment)]
</tr>
</table>
</body>
I'm not sure where goes wrong as when I automate the saveEdits() function with 'cnt' in while loop, the above code doesn't works for me. But when I defined each row clearly like below, the data the keyed-in are properly saved to each column.
function saveEdits(cnt) {
//get the editable elements.
var editElems = {
'edit1': document.getElementById('edit1').innerHTML,
'edit2': document.getElementById('edit2').innerHTML,
'edit3': document.getElementById('edit3').innerHTML,
};
alert(editElems) //print [object Object]
//save the content to local storage. Stringify object as localstorage can only support string values
localStorage.setItem('userEdits', JSON.stringify(editElems));
}
I would be much appreciate if someone can point out my mistake. The error is very much likely on saveEdits(cnt) function but I'm not sure how to fix that cause it I define each count 1 by 1, each update that being keyed-in is actually saved properly and able to retrieve when rerun. Thanks you!

JavaScript Save Table Rows added by User

I am making an Electron app that has tables, the user can add a table and change the content of the fields, but I want the input to be saved, and only if the user entered anything into them.
How would I do this? Do I need a database? Can it be done with cookies? I have tried to learn how to use cookies but have not found how to save an added element as well as the content.
function appendRow(id) {
var table = document.getElementById(id); // table reference
length = table.length,
row = table.insertRow(table.rows.length); // append table row
var i;
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('_'); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('id', style); // set DIV class attribute
div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
table {
text-align: center;
width: 400px;
}
tr:nth-child(even) {
background-color: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="test.css">
</head>
<body>
<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>
<table id="custListTop" contenteditable="false" style="background-color: #ccc;">
<tr>
<td style="border-top-left-radius: 5px;">Customers</td>
<td style="border-top-right-radius: 5px;">Main Location</td>
</tr>
</table>
<table id="custList" contenteditable="true">
<tr>
<td>Someone</td>
<td>something</td>
</tr>
</table>
<script src="test.js"></script>
</body>
</html>
Well how you are going to save it depends on what you want to do. If you want it to persist after your program was exited, you will need to save it on the disk or on a server somehow. You probably just want to save it into a file, though. (JSON is the most obvious choice). Otherwise, just save it into a js variable.
To get the data, I would either use a save button that reads the text of your cells, or use databinding. Later is very useful for Electron apps. You can either use a framework (like vue.js, react.js or many more) or DIY.
Former is probably easier and you will want a button to save it to the disk anyways. On the click of the button you can just go through all <tr>-elements and get their values and save them.
function save(id) {
var table = document.getElementById(id);
var trs = table.getElementsByTagName('tr'); // list of all rows
var values = []; // will be a (potentially jagged) 2D array of all values
for (var i = 0; i < trs.length; i++) {
// loop through all rows, each will be one entrie in values
var trValues = [];
var tds = trs[i].getElementsByTagName('td'); // list of all cells in this row
for (var j = 0; j < tds.length; j++) {
trValues[j] = tds[j].innerText;
// get the value of the cell (preserve newlines, if you don't want that use .textContent)
}
values[i] = trValues;
}
// save values
console.log(values);
}
function appendRow(id) {
var table = document.getElementById(id); // table reference
length = table.length,
row = table.insertRow(table.rows.length); // append table row
var i;
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('_'); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('id', style); // set DIV class attribute
div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
table {
text-align: center;
width: 400px;
}
tr:nth-child(even) {
background-color: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="test.css">
</head>
<body>
<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>
<button id="save" class="save" onclick="save('custList')">save</button>
<table id="custListTop" contenteditable="false" style="background-color: #ccc;">
<tr>
<td style="border-top-left-radius: 5px;">Customers</td>
<td style="border-top-right-radius: 5px;">Main Location</td>
</tr>
</table>
<table id="custList" contenteditable="true">
<tr>
<td>Someone</td>
<td>something</td>
</tr>
</table>
<script src="test.js"></script>
</body>
</html>

Random Color for <tr>

So overall I am trying to make the boxes change color when someone puts a mouse over them. Color has to be random. I know I am missing a connection point between my functions but I cant figure out what it is.
<!DOCTYPE html>
<html onmousedown='event.preventDefault();'
onmouseenter = "colorize();"
>
<head>
<title> Boxes </title>
<meta charset='utf-8'>
<style>
table {
border-spacing: 6px;
border: 1px rgb(#CCC);
margin-top: .5in;
margin-left: 1in;
}
td {
width: 40px; height: 40px;
border: 1px solid black;
cursor: pointer;
}
</style>
<script>
Create a function called colorize that is passed an element object as its
parameter and sets the elements background color style property using the
rgb(r,g,b) method setting each r,g and b to a random number between 0 and
255.
function colorize() {
var
r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
return '#' +r+g+b;
}
function colorize(co) {
document.body.style.background = co;
}
</script>
</head>
<body>
<table>
<tbody>
<script type="text/javascript">
Use document.write() and for-loops to fill in the table to create a 16x16 box table. For each td element, create a onmouseenter call to colorize, passing it the element itself (this).
var row = 16;
var cols = 16;
for(var r=0;r<row;r++){
document.write("</tr>");
for(var c=0;c<cols;c++){
document.write("<td></td>");
}
document.write("</tr>");
}
</script>
</tbody>
</table>
</body>
</html>
I'm not sure what you wanted to do with body background, nothing said about that in your text. ALos your colorizer func is overwritten. maybe you wanted something like this... ?
<!DOCTYPE html>
<html>
<head>
<title> Boxes </title>
<meta charset='utf-8'>
<style>
table {
border-spacing: 6px;
border: 1px rgb(#CCC);
margin-top: .5in;
margin-left: 1in;
}
td {
width: 40px; height: 40px;
border: 1px solid black;
cursor: pointer;
}
</style>
<script>
function colorize(el) {
var r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
el.style.backgroundColor = '#' +r+g+b;
}
</script>
</head>
<body>
<table>
<tbody>
<script type="text/javascript">
var row = 16;
var cols = 16;
for(var r=0;r<row;r++){
document.write("</tr>");
for(var c=0;c<cols;c++){
document.write("<td onMouseEnter='colorize(this);'></td>");
}
document.write("</tr>");
}
</script>
</tbody>
</table>
</body>
</html>
You need to have your colorize function update each cell in your table. Replace both colorize() and colorize(co) with one function:
function colorize() {
var r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
for (var i = 0; i < document.getElementsByTagName("td").length; i++){
document.getElementsByTagName("td")[i].style.backgroundColor = "#"+r+g+b;
}
}
i play with Ids and adding onmousedown in html tag that calls the func.
function colorize() {
var
r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
return '#' +r+g+b;
}
function change(){
var x = document.getElementById("1");
var y = document.getElementById("2");
x.style.color = colorize();
y.style.color = colorize();
}
<table frame="box" onmousedown="change()"id="1" >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
<table frame="box" onmousedown="change()" id="2" >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>February</td>
<td>$200</td>
</tr>
</table>

Javascript table is not rendering using CSS

I created a table using JavaScript, but it doesn't render using my css. so how can I make it work? actually i need more help, my idea is to create a screen that has one button and once you click on it a menu which is a table of one column starting at the top of the screen and end at the end of the screen should be showing. the table would be scrollable and each row has text (url text) with no url line under the text, so when you click on it the page open in all of the screen behind the table and the button. the button should be always showing (but it disappears when i click on it).
the main.js file is
function makeTableHTML() {
var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
var myArray = [ [ "Name, http://www.google.com" ],
[ "Name, http://www.google.com" ] ];
var result = '<table width = "300">';
for (var i = 0; i < myArray.length; i++) {
result += "<tr><td>";
if (i < 10) {
result += "0" + i + " ";
} else {
result += i + " ";
}
result += '<a href="' + myArray[i][0] + '">';
result += myArray[i][1] + "</a>";
result += "<td></tr>";
}
result += "</table>";
document.write(result);
document.getElementById("channelsmenu").classList.toggle(result);
}
function hideTableHTML() {
var x = document.getElementById('channelsmenu');
x.style.display = 'none';
}
and my html is
<!DOCTYPE html>
<html>
<head>
<title>5Star-IPTV</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/main.js"></script>
</head>
<body>
<div>
<table>
<tr>
<td>
<div id="channelsmenu" class="dropdown-content"></div>
</td>
<td class="buttons-col"><input type="image"
src="channels-menu.png" class="buttons" alt="channels menue"
onMouseOver="this.src='channels-menu-1.png'"
onMouseOut="this.src='channels-menu.png'" onclick="makeTableHTML()" /></td>
<td class="buttons-col"><input type="image"
src="return-button.png" alt="return button" class="buttons"
onMouseOver="this.src='return-button-1.png'"
onMouseOut="this.src='return-button.png'" onclick="hideTableHTML()" /></td>
</tr>
</table>
</div>
</body>
</html>
and this is the css
table {
width: 100%;
border: 1px solid black;
background-color: #808080;
}
tr {
width: 100%;
align: right;
}
th, td {
text-align: right;
} background-color: #808080;
}
.buttons-col {
text-align: center;
width: 90px;
padding-top: 5px;
}
in HTML you open "th" and close it as "tr". Secondly, please learn to write/format your code properly - it'll be easier to read your code and to help you.
Besides, use the < script > tag at the end of the HTML or run your JS in the function on event DOMContentLoaded

two td tag don't slide side by side

Hello I develop a app where td appear and disapear side by side.
lastInsertTd = 0;
function newSlidingTd() {
tr = jQuery('#myline');
var lastTd = jQuery('#myline').children().last();
td = jQuery("<td></td>")
.attr('id', 'slidingTd' + lastInsertTd+1)
.attr('style', 'display:none;vertical-align:top;width:100%');
tr.append(td);
tdSuivant = jQuery('#slidingTd' + lastInsertTd+1);
tdActuel = jQuery('#slidingTd' + lastInsertTd);
/*animation*/
tdActuel.toggle('slide', {
direction: 'left'
}, 500);
tdSuivant.toggle('slide', {
direction: 'right'
}, 500);
lastInsertTd = lastInsertTd+1;
}
table {
width:100px
}
td {
border: black solid 1px;
width:100%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<table>
<tr id="myline">
<td id='slidingTd0' onclick="newSlidingTd()">
1
</td>
</tr>
</table>
But when I call my event, my new td doesn't slide from the right but a little bit lower. How can I go through this "bug"? (this also happen when I create div inside td)
if it's slightly lower, then most likely it's some issue with displaying whitespaces.
Try setting line-height: 0; in the parent element (tr I'd guess), or remove the whitespace between < /td >< td >

Categories