Change class attribute of td by onmouseover - javascript

I'm constructing a table. And I need a <td> of table change it's attribute class to someattribute till mouse over.
How should it be?
Code:
var table = document.createElement('table');
for (var i = 1; i <=10; i++)
{
var tr = document.createElement('tr');
tr.setAttribute('id',i)
table.appendChild(tr);
for (var j = 1; j <=15; j++)
{
var td = document.createElement('td');
td.setAttribute('id',j);
// Here:
td.OnMouseOver = new function()
{
td.setAttribute("class","new");
};
tr.appendChild(td);
};
};
document.getElementById("grid").innerHTML = '';
document.getElementById("grid").appendChild(table);

You are quite close.
Use the keyword this in your onmouseover function, instead of td, which is not accessible to your function. Also, you do not need to use the keyword new to define a function.
td.onmouseover = function () {
this.setAttribute("class", "new");
};
Code:
var table = document.createElement('table');
for (var i = 1; i <= 10; i++) {
var tr = document.createElement('tr');
tr.setAttribute('id', i)
table.appendChild(tr);
for (var j = 1; j <= 15; j++) {
var td = document.createElement('td');
td.setAttribute('id', j);
td.innerHTML = ' ';
td.onmouseover = function () {
this.setAttribute("class", "new");
};
tr.appendChild(td);
};
};
document.getElementById("grid").innerHTML = '';
document.getElementById("grid").appendChild(table);
http://jsfiddle.net/samliew/VnkHB/10/

If you did want to use jQuery:
$('table td').mouseover(function() {
$(this).addClass('new');
});
This would add the class new to any <td> element in any <table> on the mouseover event.

without jQuery:
function mouseover() {
this.setAttribute("class", "new");
return true;
}
var table = document.createElement('table');
var tr, td;
for (var i = 1; i <= 10; i++) {
tr = document.createElement('tr');
tr.setAttribute('id', 'td'+i);
table.appendChild(tr);
for (var j = 1; j <= 15; j++) {
td = document.createElement('td');
td.setAttribute('id', 'tr'+j);
// Here:
td.onmouseover = mouseover;
td.innerText = "..";
tr.appendChild(td);
}
}
document.getElementById("grid").innerHTML = '';
document.getElementById("grid").appendChild(table);
function is moved to outside the loop, ids are prefixed to avoid collision
with jQuery:
function mouseover() {
this.setAttribute("class", "new");
return true;
}
function nNewElements(tag, idPrefix, n) {
var result = [];
for (var i = 1; i <= n; i++) {
result.
push($("<" + tag + ">").
attr("id", idPrefix + i)[0]);
}
return $(result);
}
$(document).ready(function () {
$("#grid").
html('').
append('<table>');
nNewElements("tr", "row", 10).
appendTo("table").
each(function () {
nNewElements("td", "data", 15).
mouseover(mouseover).
text("..").
appendTo($(this));
});
});

Related

How can I set an image as an td background?

I'm trying to set each td as a different image that I have saved as imgn.gif. (n being image number, I have 13 images, img1.gif., img2.gif... img13.gif) I have a code that generates the table now I just can't figure out how to set a background image, preferably so that the n imgn.gif changes to the next index so the next td will have the next image.
this is the code that I have for now. I assume I have to set something differently here: const cellText = document.createTextNode(2);, so it sets background-image instead?
function options ()
{
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
for (let i = 0; i < 1; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 16; j++) {
const cell = document.createElement("td");
const cellText = document.createTextNode(2);
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
just add 5 lines in you actual code:
options();
function options() {
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
const nbImage = 13;
let curImage = 1;
for (let i = 0; i < 1; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 16; j++) {
const cell = document.createElement("td");
if (curImage > nbImage) {
curImage = 1;
}
cell.style.backgroundImage = 'url(img' + curImage + '.gif)';
const cellText = document.createTextNode(2);
cell.appendChild(cellText);
row.appendChild(cell);
curImage += 1;
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}
I've added:
nbImage (13 from your post)
curImage to iterate through your 13 images
After your cell creation, checking the image number:
if (curImage > nbImage) {
curImage = 1;
}
So your fourteenth TD will have the image 1
Your is already created as a DOM element so you can refer it and add a background image:
cell.style.backgroundImage = 'url(img' + curImage + '.gif)';
That will add for each TD a backgound image "img1.gif", "img2.gif"... till "img13.gif", after "img1.gif" ... and so on...
You can create a variable (nImage for exemple) starting from 1 to 13 and reset it when up to 13 so it came back to 1. Then use this variable to modify style.backgroundImage of your td :
function options ()
{
const tbl = document.createElement("table");
const tblBody = document.createElement("tbody");
let nImage = 1 ;
for (let i = 0; i < 1; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 16; j++) {
const cell = document.createElement("td");
const cellText = document.createTextNode(2);
if (nImage > 13){nImage =1 ;}
cell.style.backgroundImage = "url('yourPathTo/img"+nImage + ".gif')" ;
nImage++ ;
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
document.body.appendChild(tbl);
}

How to create a working identifier for the cells of this table?

I'm trying to give each cell of a table an identifier like in this photo
this is what I tried but it's not working:
function init() {
var board = document.createElement('table');
board.setAttribute("border", 1);
board.setAttribute("cellspacing", 0);
board.setAttribute("id", 'tbl');
var identifier = 0;// <-------
for (var i = 0; i < GRID_SIZE; i++) {
var row = document.createElement('tr');
board.appendChild(row);
for (var j = 0; j < GRID_SIZE; j++) {
var cell = document.createElement('td');
cell.setAttribute('height', 20);
cell.setAttribute('width', 20);
cell.classList.add('col' + j, 'row' + i);
cell.identifier = identifier; // <-------
row.appendChild(cell);
identifier += identifier;// <--------this is the problem
}
}
document.getElementById("main").appendChild(board);
}
First of all, instead of custom properties you should use data attributes and instead of the width and height attributes you should use CSS. Second, you were incrementing identifier by itself, so it wouldn't grow from 0.
const GRID_SIZE = 6;
function init() {
var board = document.createElement('table');
board.setAttribute("border", 1);
board.setAttribute("cellspacing", 0);
board.setAttribute("id", 'tbl');
var identifier = 0;
for (var i = 0; i < GRID_SIZE; i++) {
var row = document.createElement('tr');
board.appendChild(row);
for (var j = 0; j < GRID_SIZE; j++) {
var cell = document.createElement('td');
cell.dataset.identifier = identifier;
cell.innerText = identifier;
row.appendChild(cell);
identifier++;
}
}
document.getElementById("main").appendChild(board);
}
init();
main>table td {
width: 20px;
height: 20px;
}
<main id="main"></main>
Also, you don't need to store the coordinates of the cell, since you can calculate them from the identifier like this:
row = Math.floor(identifier / GRID_SIZE);
column = identifier % GRID_SIZE;
GRID_SIZE*i+j;
put it inside the cell using cell.innerHTML=GRID_SIZE*i+j;
function init(GRID_SIZE) {
var board = document.createElement('table');
board.setAttribute("border", 1);
board.setAttribute("cellspacing", 0);
board.setAttribute("id", 'tbl');
var identifier = 0; // <-------
for (var i = 0; i < GRID_SIZE; i++) {
var row = document.createElement('tr');
board.appendChild(row);
for (var j = 0; j < GRID_SIZE; j++) {
var cell = document.createElement('td');
cell.setAttribute('height', 20);
cell.setAttribute('width', 20);
cell.innerHTML = GRID_SIZE * i + j;
cell.classList.add('col' + j, 'row' + i);
cell.identifier = identifier; // <-------
row.appendChild(cell);
identifier += identifier; // <--------
}
}
document.getElementById("main").appendChild(board);
}
init(10)
<div id="main"></div>

InnerHTML changes old variables

I'm doing a function that creates a table in JS.
I create a variable table_row fill it and then add table_layout.appendChild(table_row); it to the table_layout element.
Next, I clean it table_row through innerHTML='', but when cleaning, the variable that I ALREADY added to the element table_layout is also cleared.
Why is this happening?
Should the added element be cleared?
How can this be avoided?
Look at the CODE.
var columns = ["col1", "col2", "col3"];
var rows = 5;
function Table() {
var table_layout = document.createElement("table");
var table_row = document.createElement("tr");
for (var i = 0; i < columns.length; i++) {
// main row
table_row.innerHTML += "<th>" + columns[i] + "</th>";
}
table_layout.appendChild(table_row); //add in table element
// table_row.innerHTML = ""; //If you uncomment this line, then we get an empty output!
//refresh table_row html, that would generate a new line
//But when cleaning. Cleared in the previously added item in table_layout .... how??
// for (var j = 0; i < columns.length; j++) {
// table_main_row.innerHTML += '<td></td>';
// }
// for (var i = 0; i < rows; i++) {
// table_layout.appendChild(table_row);
// }
return table_layout;
}
var div = document.getElementById("qqq");
div.appendChild(Table());
#qqq {
background: red;
}
<div id="qqq"></div>
The table_row variable contains a reference. You will need to create a new element for each row.
// creates a DOM Element and saves a reference to it in the table_row variable
var table_row = document.createElement("tr");
// updates the DOM Element through the reference in the table_row variable
table_row.innerHTML += "<th>" + columns[i] + "</th>";
// still references the DOM Element, so you are clearing its content
// table_row.innerHTML = "";
You will need to . . .
// create a new DOM Element to use
table_row = document.createElement("tr");
// then update its contents
table_main_row.innerHTML += '<td></td>';
. . . for each iteration.
See JavaScript on MDN for tutorials, references, and more.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" language="javascript">
var columns = ["col1", "col2", "col3"];
var rows = 5;
function createNewRow(headerRow)
{
var newRowElem = null;
try
{
newRowElem = document.createElement("tr");
for (var i = 0; i < columns.length; i++)
{
if(headerRow) newRowElem.innerHTML += "<th>" + columns[i] + "</th>";
else newRowElem.innerHTML += "<td>" + columns[i] + "</td>";
}
}
catch(e)
{
alert("createNewRow Error" + e.Message);
}
finally
{
}
return newRowElem;
}
function Table()
{
var table_layout = null;
try
{
table_layout = document.createElement("table");
// Create Header Row
table_layout.appendChild(createNewRow(true));
// Create Other Rows
for (var i = 0; i < rows; i++)
{
table_layout.appendChild(createNewRow(false));
}
}
catch(e)
{
alert("Table Error: " + e.Message);
}
finally
{
}
return table_layout;
}
</script>
<style>
#qqq {
background: red;
}
</style>
</head>
<body>
<div id="qqq"></div>
<script type="text/javascript" language="javascript">
var div = document.getElementById("qqq");
div.appendChild(Table());
</script>
</body>
</html>
I did so.
var table_layout = document.createElement('table');
table_layout.setAttribute('id', 'main_table');
table_layout.setAttribute('border', '1');
var row = document.createElement('tr');
row.setAttribute('class', 'main_row');
for (var i = 0; i < this.fields.length; i++) { // строка с именами столбцов
var th = document.createElement('th');
th.setAttribute('class', 'cell_name');
th.innerHTML = this.fields[i];
row.appendChild(th);
}
table_layout.appendChild(row); //добавляем
row = document.createElement('tr'); // очищаем от старых элементов строку (переопределяем)
row.setAttribute('class', 'table_row');
var td = document.createElement('td');
td.setAttribute('class', 'table_cell');
// td.setAttribute('ondblclick', 'input_func()');
td.addEventListener('click', function () {
alert();
});
td.innerHTML='000';
for (var j = 0; j < this.fields.length; j++) { // создаем строку с N-количеством ячеек
row.appendChild(td.cloneNode(true));
}
for (var i = 0; i < this.rows; i++) { // Добавляем её есколько раз через клона
table_layout.appendChild(row.cloneNode(true));
}
But then redistribution with functions for the table.
var table_layout = document.createElement('table');
table_layout.setAttribute('id', 'main_table');
table_layout.setAttribute('border', '1');
var row = table_layout.insertRow(0);
var cell;
for (var j = 0; j < this.fields.length; j++) {
cell = row.insertCell(j);
cell.outerHTML = '<th>' + this.fields[j] + '</th>';
cell.className = 'cell_name';
}
for (var i = 0; i < this.rows; i++) {
row = table_layout.insertRow(i + 1);
row.className = 'row_table';
for (var n = 0; n < this.fields.length; n++) {
cell = row.insertCell(n);
// cell.innerHTML = '00';
cell.className = 'table_cell';
cell.innerHTML = '&nbsp';
}
}
return table_layout;

How "tblGene()" call on JavaScript page.I am want to call on HTML page using onclick.. Without click this Json table show on my web page

How tblGene() call on JavaScript page. I do not want to call on HTML page using onclick. Without click, this JSON table show on my web page. Please help me. When page was loaded this JSON table on my web page. I do not want to use input box for click.
<input type="button" onclick="tblGene()" value="Click Here to Generate Table" style="width:100% height:100%" />
<div id="showData"></div>
var people, asc1 = 1;
function tblGene() {
var data = [{"rollno":1234,'name': "jetta",'marks': 600,'percentage': 1222,'bestscore': 99},{"rollno":2341,'name': "jetta",'marks': 700,'percentage': 1222,'bestscore': 100},{"rollno":3421,'name': "jetta",'marks': 500,'percentage': 1222,'bestscore': 90},{"rollno":4321,'name': "jetta",'marks': 400,'percentage': 1222,'bestscore': 95},{"rollno":2043,'name': "jetta",'marks': 550,'percentage': 1222,'bestscore': 80},];
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
tbody.id = "people";
var tbl = document.createElement("table");
tbl.id = "tblSample";
var col = [];
for (var i = 0; i < data.length; i++) {
for (var colHdr in data[i]) {
if (col.indexOf(colHdr) === -1) {
col.push(colHdr);
}
}
}
var tr = tbl.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
th.dataset.key = i;
tr.appendChild(th);
}
thead.appendChild(tr);
for (var i = 0; i < data.length; i++) {
tr = tbl.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var td = document.createElement("td");
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
tbody.appendChild(tr);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
var divCntr = document.getElementById("showData");
divCntr.innerHTML = "";
divCntr.appendChild(tbl);
thead.addEventListener("click", function(event) {
var key = event.target.dataset.key;
people = document.getElementById("people");
sort_tbl(people, key, asc1);
});
function sort_tbl(tblSample, key, asc) {
var rows = tblSample.rows,
rlen = rows.length,
arr = new Array();
for (var i = 0; i < rlen; i++) {
var cells = rows[i].cells;
var clen = cells.length;
arr[i] = new Array();
for (var j = 0; j < clen; j++) {
arr[i][j] = cells[j].innerHTML;
}
}
arr.sort(function(x, y) {
if (isNaN(x[key]) && isNaN(y[key])) {
var a = String(x[key]).toUpperCase();
var b = String(y[key]).toUpperCase();
if (a > b)
return 1
if (a < b)
return -1
return 0;
} else {
return x[key] - y[key];
}
});
for (i = 0; i < rlen; i++) {
rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
}
}
}
Just remove the () from you onclick handler, like this onclick="tblGene".
If you leave the (), you're executing the function as soon as the <input> element is loaded - in your case on page load.

How to check value of table td?

I am trying to create mine field game. "I am very new to Js".
What I have done so far:
var level = prompt("Choose Level: easy, medium, hard");
if (level === "easy") {
level = 3;
} else if (level === "medium") {
level = 6;
} else if (level === "hard") {
level = 9;
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 12 + 1);
if (j < level) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + " ");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
So I create here 2d table and enter 2 random values in rows and columns (mined or clear).
Where I am stuck is:
Check if td = mined it dies otherwise open the box(td) etc.
How do I assign value of td? I mean how can I check which value(mined/clear) there is in the td which is clicked?
Ps: Please don't write the whole code:) just show me the track please:)
Thnx for the answers!
Ok! I came this far.. But if I click on row it gives sometimes clear even if I click on mined row or vice versa!
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id','myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for(var i=1;i<=10;i++)
{
var row = document.createElement("tr");
document.write("<br/>" );
for(var x=1;x<=10;x++)
{
var j=Math.floor(Math.random()*12+1);
if(j<level)
{
j = "mined";
}
else{
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "2");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
if(id === "mined")
{
alert("You died");
}else
{
alert("clear");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
I think I do something wrong with giving the table id "myTable"..
Can you see it?
Thank you in advance!
So, the idea would be:
assign a click event to each td cell:
td.addEventListener('click', mycallback, false);
in the event handler (callback), check the content of the td:
function mycallback(e) { /*e.target is the td; check td.innerText;*/ }
Pedagogic resources:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td?redirectlocale=en-US&redirectslug=HTML%2FElement%2Ftd
https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
JavaScript, getting value of a td with id name

Categories