Dynamically highlight td in a table - javascript

Problem
How to highlight dynamically a selected td?
Codepen
Pen here
Code
The map is a 2d array random generated, something like this:
map = [[1,1,1,1,0],
[1,0,0,0,0],
[1,0,1,1,1],
[1,0,0,0,1],
[1,1,1,0,1]]
I can move the player 3 squares per turn and, one of this squares is his actual position. I used this function to call the movement:
function movements(character){
var possibleMovement=3;
let coord=character.actualPosition;
let row = $($("#tableGame tr")[coord.row]);
let cell = $($("td", row)[coord.cell]);
forward(row, cell, possibleMovement, character);
backward(row, cell, possibleMovement, character);
goUp(row, cell, possibleMovement, character);
goDown(row, cell, possibleMovement, character);
};
and with the functions below I try to highlight the cells where the character can actually move.
function forward(row, cell,possibleMovements, character){
for(var i = 0; i<possibleMovements; i++){
cell = $($("td", row)[coord.cell+i]);
var tile = $(".tile", cell).addClass('possibleSteps');
};
};
function backward(row, cell, possibleMovements, character){
for(var i = 0; i>=possibleMovements; i--){
console.log('sei qua');
cell = $($("td", row)[coord.cell+i]);
var tile = $(".tile", cell).addClass('possibleSteps');
};
};
Task
I need to highlight the tiles near the character:
Two tiles above character.actualPosition
Two tiles below
Two tiles at his right
Two tiles at his left
These are the two " testing function "
function forward(row, cell,possibleMovements, character){
for(var i = 0 ; i<possibleMovements; i++){
cell = $($("td", row)[coord.cell +i]);
var tile = $(".tile", cell).addClass('possibleSteps');
console.log([coord.row] + "<<<row" + [coord.cell+i] + "<<<cell");
};
};
function backward(row, cell, possibleMovements, character){
possibleMovements= possibleMovements*-1;
for(var i = 0 ; i>possibleMovements; i--){
cell = $($("td", row)[coord.cell+i]);
var tile = $(".tile", cell).addClass('possibleSteps');
console.log([coord.row] + "<<<row" + [coord.cell-i] + " <<<cell");
};
};

Finally i found an answer. I want to say thanks to this post because it helps me a lot to find a solution that works.
The final functions to highlight the tiles near the character are these
function movements(){
let possibleMovement=3;
let row = character.actualPosition.row;
let cell = character.actualPosition.cell;
forward(possibleMovement, row, cell);
backward(possibleMovement, row, cell);
goUp(possibleMovement, row, cell);
goDown(possibleMovement, row, cell);
};
function forward(possibleMovements, row, cell){
let charRow = row;
let charCell= cell;
var table = $("table")[0];
for(var i = 0; i<possibleMovements; i++){
let cell = table.rows[charRow].cells[charCell+i]; // This is a DOM "TD" element
let $cell = $(cell);
$(cell).addClass('possibleSteps');
};
};
function backward(possibleMovements, row, cell){
let charRow = row;
let charCell= cell;
var table = $("table")[0];
for(var i = -1; i>(possibleMovements*-1); i--){
let cell = table.rows[charRow].cells[charCell+i]; // This is a DOM "TD" element
let $cell = $(cell);
$(cell).addClass('possibleSteps');
};
};
function goUp(possibleMovements, row, cell){
let charRow = row;
let charCell= cell;
var table = $("table")[0];
for(var i = -1; i>(possibleMovements*-1); i--){
let cell = table.rows[charRow+i].cells[charCell]; // This is a DOM "TD" element
let $cell = $(cell);
$(cell).addClass('possibleSteps');
};
};
function goDown(possibleMovements, row, cell){
let charRow = row;
let charCell= cell;
var table = $("table")[0];
for(var i = -1; i<possibleMovements; i++){
let cell = table.rows[charRow+i].cells[charCell]; // This is a DOM "TD" element
let $cell = $(cell);
$(cell).addClass('possibleSteps');
};
};
The main solution was to understand this 4 lines of code, and how i can iterate through them:
var table = $("table")[0];
let cell = table.rows[charRow].cells[charCell+i]; // This is a DOM "TD" element
let $cell = $(cell);
$(cell).addClass('possibleSteps');

Related

How to dynamically add <a> in a html table?

I have a table generated from an array. I'm looking to add a hyperlink to the entire first column of the <tbody> and only the first column.
I am able to add the <a> after the table is created, but then it doesn't actually contain the url within it, it simply appends to what already exists.
Specifically, how can I add a hyperlink to the first column of the
<tbody>?
Generally, as the table is being made, how can I specify different
things (anchors, classes, styles, etc.) for different columns?
http://jsfiddle.net/nateomardavis/n357gqo9/10/
$(function() {
google.script.run.withSuccessHandler(buildTable)
.table();
});
//TABLE MADE USING for
function buildTable(tableArray) {
var table = document.getElementById('table');
var tableBody = document.createElement('tbody');
var tbodyID = tableBody.setAttribute('id', 'tbody');
for (var i = 0; i < tableArray.length; ++i) {
var column = tableArray[i];
var colA = column[0];
var colB = column[1];
var colC = column[2];
var colD = column[3];
if (colA != "") {
var row = document.createElement('tr');
var getTbody = document.getElementById('tbody');
for (var j = 0; j < column.length; ++j) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(column[j]));
row.appendChild(cell);
//NEXT TWO LINES DO NOT WORK
var firstCol = getTbody.rows[i].cells[0];
firstCol.setAttribute('class', 'TEST');
}
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
document.body.appendChild(table);
/* WORKS AFTER TABLE IS CREATED BUT CAN'T CAPUTRE INTERNAL LINK
var getTbody = document.getElementById('tbody');
for (var i = 0; i < getTbody.rows.length; i++) {
var firstCol = getTbody.rows[i].cells[0]; //first column
//firstCol.style.color = 'red';
//firstCol.setAttribute('class', 'TEST');
var link = document.createElement('a');
firstCol.appendChild(link);
}
*/
}

How to get innerHTML of td in dynamically populated table in JavaScript

I created a table and populated values from an array, so I have 5x5 table, where each td will be filled with a word. The word come from array memo and all the code below works fine.
var myTableDiv = document.getElementById("results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
table.border = '1'
table.appendChild(tableBody);
//TABLE ROWS
for (i = 0; i < this.memo.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < this.memo[i].length; j++) {
var td = document.createElement('TD');
td.onclick = function () {
check();
}
td.appendChild(document.createTextNode(this.memo[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table);
I have one question : I would like to click on the cell and get the word, which belongs to the cell.
For this purpose I tried onclick as I created td element
td.onclick = function () {
check();
}
The function check should print the innerHTML of the cell, which was clicked
function check() {
var a = td.innerHTML;
console.log(a);
}
But it gives me always wrong text - the last one in the array, which was populated.
How could I solve it?..
You always get the last td in the array because the last value that was set to td was of the last cell. You need to add the a parameter, say event, to onclick's callback function, and then your clicked element will be referenced in event.target. Then you would be able to get it's innerHTML.
Here's why it's always giving you the first element: after the for (j = 0; ... loop is finished, the variable td will hold the value of the last element in the list. Then, when check is called, it accesses that same td variable pointing to the last element.
To solve this, you can add an argument to the function to accept a specific element and log that.
td.onclick = function () {
check(td);
};
// later...
function check(element) {
var html = element.innerHTML;
console.log(html);
}
I would pass the innerHTML in the click itself - please see working example below, with some mock data for memo.
var myTableDiv = document.getElementById("results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
var memo = [
['joe', 'tom', 'pete'],
['sara','lily', 'julia'],
['cody','timmy', 'john']
]
table.border = '1'
table.appendChild(tableBody);
//TABLE ROWS
for (i = 0; i < this.memo.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < this.memo[i].length; j++) {
var td = document.createElement('TD');
td.onclick = function () {
check(this.innerHTML);
}
td.appendChild(document.createTextNode(this.memo[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table);
function check(a) {
console.log(a);
}
<div id="results">
</div>
you can try..
td.onclick = function () {
check();
}
to
td.onclick = function (evt) {
var html = evt.target.innerHTML;
console.log(html);
check(html); //to do something..
}

How to find out which row was clicked?

Hello i generate a Table with javascript and now i wont to find out which row and column the user has clicked?
Here are my function for the table:
function doNextSteps() {
removeAustriaFromCountries();
//insert table
var table = document.createElement("table");
table.setAttribute('id', 'matrixTable');
table.setAttribute('class', 'jbiTable');
// insert MATRIX row
var matrixRow = table.insertRow();
var cell = matrixRow.insertCell(); // left column for countries
cell.setAttribute('class', 'jbiMatrixCell');
cell.setAttribute('colSpan', departments.length + 1);
cell.appendChild(document.createTextNode("MATRIX"));
// insert departments row
var departmentsRow = table.insertRow();
var cell = departmentsRow.insertCell(); // left column for countries
cell.setAttribute('class', 'jbiBlankCell');
for (var i = 0; i < departments.length; i++) {
var cell = departmentsRow.insertCell();
cell.appendChild(document.createTextNode(departments[i].name));
cell.setAttribute('class', 'jbiDepartmentCell');
}
for (var i = 0; i < countries.length; i++) {
var countryRow = table.insertRow();
var cell = countryRow.insertCell(); // left country column
//cell.appendChild(document.createTextNode(countries[i].name));
var img = document.createElement('img');
img.src = "example.com + flags[i].name";
cell.appendChild(img);
cell.setAttribute('class', 'jbiCountryCell');
for (var j = 0; j < departments.length; j++) {
var cell = countryRow.insertCell();
var img = document.createElement('img');
img.src = "https://intranet.windkraft.at/OrganisationManual/Documents/Kreis.jpg";
img.onclick = function () {
window.location.href = "example.com" + pdfFiles[i].name;
};
cell.appendChild(img);
cell.setAttribute('class', 'jbiCircleCell');
}
}
$("#divTable").append(table);
}
The table gets generated and now i want to know in which header and in which column the user has clicked. With that information i want to make a new query to get files dynamically displayed in the Table. Any help would be great. And thanks for your Help.
To get the index of the row, you can use this code in your event listener function:
function onClick() {
var cell = this;
var row = cell.parentNode;
var cellIndex = Array.prototype.indexOf.call(row.children, cell);
var rowIndex = Array.prototype.indexOf.call(row.parentNode.children, row);
// do stuff with rowIndex, cellIndex
// rowIndex is the row number starting with row 0
// cellIndex is the column number starting with column 0
}
You can use parentNode.rowIndex & cellIndex to get the cell & rowIndex
document.getElementsByTagName('table')[0].addEventListener('click', function(e) {
console.log(e.target.parentNode.rowIndex,' ',e.target.cellIndex);
}, false);
Check this jsFiddle

MineField with Js

I am trying to create a minefield game with javascript.
When I click on clear ro**w it gives "passed" but sometimes "died" too or clicking on **mined row gives sometimes "passed". It's supposed to give only "passed" with clear and "died" with mined row.
I can't figure out the reason..
Could you see it?
Here is my code so far:
var level = 9;
// 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() * 50);
if (j <= 15) {
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", "1");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("td");
for (p = 0; p < rows.length; p++) {
var currentRow = table.rows[p];
var createClickHandler = function (row) {
return function () {
var cell = row.getElementsByTagName("td")[1];
var id = cell.innerHTML;
if (id == "mined") {
alert("Died");
} else {
alert("Passed!");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
JSFiddle Here:
http://jsfiddle.net/blowsie/ykuyE/
Thanks in advance!
Its' this line, which causes the faulty behaviour: var cell = row.getElementsByTagName("td")[1]; Everytime a click is made, the [1] selects the 2nd cell of a column, no matter which cell was actually clicked.
I modified your fiddle: http://jsfiddle.net/ykuyE/1
The onclick handler is now applied to the individual cell directly, when the table is created.
cell.onclick = function() {
if (this.innerHTML == "mined") {
alert("Died");
} else {
alert("Passed!");
}
}

Adding ledger totals in multiple TDs

This code generates a ledger. I narrowed it down to the minimum. By clicking a plus sign it adds an additional row to the ledger.
I'm looking to add each total of the variable newAmount and locate its updated total in a TD to the right of each row. I created newAmount.id = "mainAmount"; to create unique IDs thinking this would help.
var mainNumber = 0;
function addElement()
{
//add a number for each row
mainNumber++;
//create each row, id each slot, and add it where it goes
newDiv = document.createElement("div");
newDiv.id = "main";
newTable = document.createElement("table");
newTable.id = "mainTable";
newDiv.appendChild(newTable);
newTr = document.createElement("tr")
newTr.id = (mainNumber);
newTr.className = "mainRow";
newTable.appendChild(newTr);
newAmount = document.createElement("td");
newAmount.id = "mainAmount";
newAmount.className = (mainNumber);
newPlus = document.createElement("td");
newPlus.id = "mainPlus";
newTotalTable = document.createElement("table");
newDiv.appendChild(newTotalTable);
newTotalTable.id = "mainTotalTable";
newTotalTr = document.createElement("tr");
newTotalTable.appendChild(newTotalTr);
newTotalTr.id = "mainTotalTr";
newTotalTd = document.createElement("td");
newTotalTd.id = "mainTotalTd" + (mainNumber);
newTr.appendChild(newAmount);
newTotalTr.appendChild(newTotalTd);
//whats default inside of each slot
newAmount.innerHTML = '<form name="formAmount"><textarea name="textAmount" size="25" onfocus="wait();" id="amount' + (mainNumber) + '">0</textarea>';
newTr.appendChild(newPlus);
//click this to add a row
newPlus.innerHTML = '<img src="images/plus.png">';
// add the newly created element and it's content into the DOM
my_div = document.getElementById("mainAnchor");
document.body.insertBefore(newDiv, my_div);
}
//doesn't work...trying to hover over any row and show var idName in console
function trHover(){
$('tr').hover(function() {
var idName = $('tr'+'#'+(mainNumber)).attr('id');
console.log(idName);
});
}
//when you focus on amount box, this is activated, which adds attribute onblur and stars addTotal
function wait(){
var blurred = $(this).attr("onblur");
blurred = addTotal();
}
//adds total and displays it in td to the right
function addTotal(){
var y = 1;
var sum = 0;
var input;
while( ( input = document.getElementById( 'amount'+y ) ) ) {
sum += parseInt( input.value );
++y;
console.log(sum);
$("#mainTotalTd1").text(sum);
}
}
Rather than adding a single row, it looks like clicking the plus sign adds a div and two tables, so I'm not sure what you are going for there. I can fix the hover function, though:
$('tr').hover(function() {
var idName = $(this).attr('id'); // 'this' is the element being hovered
console.log(idName);
});

Categories

Resources