How to generate a table of colors? - javascript

I'm trying to create a table with 32 buttons.
Each button generated must have the name of a color (in turn generated for the button).
If I click on the button, placed in the table, the page background color should be with the text (color) displayed on the pressed button.
I thought about this:
var tableRef = document.getElementById('table').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.id = "row"
Can you do this?
What advice could you give me the components to be used?
I making this in Javascript code.

Advice:
Create the entire thing using Javascript.
function createTable(){
var body=document.getElementsByTagName('body')[0];
var tbl=document.createElement('table');
tbl.setAttribute('id', tableID);
var tbdy=document.createElement('tbody');
for(var i=0;i<4;i++){
var tr=document.createElement('tr');
for(var j=0;j<8;j++){
var td=document.createElement('td');
var bt = document.createElement('button');
// add button attributes
td.appendChild(bt);
tr.appendChild(td)
}
}
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl)
}
then you create the onclick method
function changeColor(color){
var body=document.getElementsByTagName('body')[0];
body.style.bgColor = color;
}
Mind you I'm doing this from memory, if the bgcolor doesn't work then try something else

Related

Why does my button click listener not work in chrome extension?

I'm trying to create a chrome extension, my problem is that when I try to place an event listener to each button in a class, only the first button has one, and the rest don't have an event listener.
function copyButtonInitialise(){
var copyButtons = document.getElementsByClassName("copyPassword");
console.log("length = ", copyButtons.length);
for (var i = 0; i < copyButtons.length; i++){
console.log(copyButtons[i] + " element number " + i + "= button");
copyButtons[i].addEventListener("click", copyButtonClick);
}
}
This function is what should be called if any button with the class "copyPasword" is clicked.(just want to make sure it gets clicked, but it doesn't)
function copyButtonClick(){
console.log("Hello There");
}
This is the function that loads passwords, it's called before adding event listeners to buttons.
async function loadPasswords(){
document.getElementById("passwordTable").innerHTML = "";
console.log("This is the loadpasswords function");
chrome.storage.sync.get(null, function(items) {
var allKeys = Object.keys(items);
var passwordTable = document.getElementById("passwordTable");
var header = passwordTable.createTHead();
var passwordRow = header.insertRow(0);
for(var i = 0; i < allKeys.length; i++){
let passwordKey = allKeys[i];
chrome.storage.sync.get([allKeys[i]], function(value){
var passwordName = Object.keys(value);
passwordName = passwordName[0];
var table = document.getElementById("passwordTable");
var header = table.createTHead();
var passwordRow = header.insertRow(0);
var cellTwo = passwordRow.insertCell(0);
var cell = passwordRow.insertCell(1);
cellTwo.innerHTML = "<p1 id=passwordNameCol>" + passwordName + "</p1>";
cell.innerHTML = "<button class=copyPassword> Copy " + '"'+ passwordName + '"'+ "</button>";
});
}
});
}
The passwords clearly load in.
When I click the buttons, nothing gets sent to the console, expecting a "hello there" (as shown above)
Try these things:
the outer chrome.storage.sync.get(null returns all stored couples key+value.
Why you use chrome.storage.sync.get a second time inside the "for" statement? It is not necessary.
Don't use insert methods of table but try with createElement and appendChild.
Create first an THEAD (or TBODY) element and then put every rows on it.
When you'll finish you'll have to append only that THEAD\TBODY as child of your table.
Try to create the button with createElement (as i suggest for any other table elements) and after its creation put the event listener on it (inside the "for").
if you think to reuse the same table for other differente rows remenber to destroy the THEAD first otherwise the just created events listeners will remain orphans.
Destroy the THEAD with something like element.remove() and not with innerHTML = "".

How to add event listener to buttons in a loop

I'm new to javascript and I'm trying to create a menu of buttons. In the menu, I want to add event listeners when I click a button.
My problem is I'm not sure how to implement it, to make it possible to target each button with the specific code that button need to run.
I have a button that needs to turn red when clicked and another that needs to load another site. How is it possible to achieve these things.
At the moment I generate the Buttons from a JSON document and create them in the code you can see below.
EDIT: added id attribute to javascript
function createMenu(jsonObj) {
let menu = jsonObj["menuitems"];
console.log(menu[0]);
let table = document.createElement("table");
for (let i = 0; i < menu.length; i++) {
let tableSection = document.createElement("tr");
let tableItem = document.createElement("td");
tableSection.appendChild(tableItem);
let button = document.createElement("BUTTON");
tableItem.appendChild(button);
let text = document.createTextNode(menu[i].item);
button.appendChild(text);
button.classList.add("menuButtons");
table.appendChild(tableSection);
button.setAttribute("id", menu[i].id);
button.addEventListener("click",/*What do i write here*/);
}
document.getElementById("menuDiv").appendChild(table);
}
Standards advice to not declare variable in loop. You can make an attribute (data-horsSujet) and compare the value to know what to do. Like this :
function createMenu(jsonObj) {
const menu = jsonObj["menuitems"];
console.log(menu[0]);
const table = document.createElement("table");
const myfct = function (event) {
const button = event.target;
if (button.getAttribute("data-horsSujet") == 1)
button.style.color = "red";
else
document.location = "google.fr";
}
for (let i = 0, tableSection, tableItem, button, text; i < menu.length; i++) {
tableSection = document.createElement("tr");
tableItem = document.createElement("td");
tableSection.appendChild(tableItem);
button = document.createElement("BUTTON");
tableItem.appendChild(button);
text = document.createTextNode(menu[i].item);
button.appendChild(text);
button.classList.add("menuButtons");
table.appendChild(tableSection);
button.setAttribute("id", menu[i].id);
button.addEventListener("click", myfct);
button.setAttribute("data-horsSujet", i);
}
document.getElementById("menuDiv").appendChild(table);
}

Replacing entire DIV with function

I'm attempting to start a div area with html in it and then replace that html with new html. I am currently trying to do so with the use of a function to simplify the creation of the html.
This is my function that creates a table based on input of rows and columns and a character.
function drawArt (x, y, char){
$( "#artArea").append("<table>");
indexY = 0;
while (indexY < y)
{
$( "#artArea").append("<tr>");
var indexX = 0;
while (indexX < x)
{
$( "#artArea").append("<td class=tableCell>" + char + "</td>");
indexX++;
}
$( "#artArea").append("</tr>");
indexY++;
}
$( "#artArea").append("</table>")
};
I'd like to be able to recall this function to redraw the table. So far this is what I have written but it seems to not work. Any tips?
$( "#genNew" ).click(function(){
var xGlobal = $("#numCols").val();
var yGlobal = $("#numRows").val();
var charGlobal = $("#drawChar").val();
$( "#artArea" ).replaceWith();
drawArt (xGlobal, yGlobal, charGlobal);
})
So, as suggested below changing "replaceWith" to "empty" fixed part of my problem. However, it broke another part of my program. I should be able to click on any character and get it to change to whatever was input, without changing the whole table, as so:
$( ".tableCell" ).click(function(){
charGlobal = $("#drawChar").val();
$(this).text(charGlobal)
})
Which part of my program is failing?
The big problem is you're creating invalid html. You always append to the #artArea table, so your markup will end up as
<table>
<tr></tr>
<td></td>
<td></td>
... etc
</table>
This is not what you want. What I suggest you could do is to simply create the appropriate html as a string inside drawArt and use `replaceWith to change the html
function drawArt (x, y, char){
var html = "<table>";
indexY = 0;
while (indexY < y)
{
html += "<tr>";
//-- snip, you get the idea!
}
html += "</table>"
return html;
}
and then
$( "#genNew" ).click(function(){
var xGlobal = $("#numCols").val();
var yGlobal = $("#numRows").val();
var charGlobal = $("#drawChar").val();
$( "#artArea" ).html(drawArt (xGlobal, yGlobal, charGlobal));
})
Working example: http://jsfiddle.net/0sh1wt01/1/
Having updated the question with a new requirement, I should address that too. The reason your click event handler does not work on the table cells is that click only affects elements which are on the page at the time the page loads. if you're dynamically adding new elements (as we are above) then you need to delegate the event to an element which does exist at page load. In this case we could use the artArea. Note you want .html not .text
$( "#artArea" ).on('click','.tableCell', function(){
charGlobal = $("#drawChar").val();
$(this).html(charGlobal);
});
Live example: http://jsfiddle.net/0sh1wt01/2/
You can replace the html with a new one.
This is the js code:
$("#start").click(function() {
var x = $("#rows").val(),
y = $("#columns").val(),
charx = $("#char").val();
//getting teh no of columns, rows and the character
$("#container").html("");
//empty the container first
var table = document.createElement("table");
for (var i = 0; i < x; i++) {
var tr = document.createElement("tr");
for (var j = 0; j < y; j++) {
var td = document.createElement("td");
td.innerHTML = charx;
tr.appendChild(td);
}
table.appendChild(tr);
}
//creating the table based on the values
$("#container").append(table);
//appending inside the container
});
Here is the Plnkr Link
Hope it works for you :)

Create Element with onclick

I have a table, and each row is added through JavaScript. I create these rows so that when they're clicked another cell will be created beneath them where I can display additional information. Now I want to be able to destroy the row I just created when the user clicks a button etc. So essentially, I need to be able to have the row I created have an onclick attribute, but it doesn't seem to work... I've tried everything I can think of so any help would be awesome!
var table = document.getElementById("main_table");
var row = table.insertRow(1);
row.id = count;
row.onclick = function ()
{
var id = this.id;
var target = document.getElementById(id);
var newElement = document.createElement('tr');
newElement.style.height = "500px";
newElement.id = id + "" + id;
//newElement.innerHTML = text;
target.parentNode.insertBefore(newElement, target.nextSibling );
//var newRow = document.createElement("tr");
//var list = document.getElementById(id);
//list.insertAfter(newRow,list);
var newRow = table.insertRow(newID);
}
I have tried to mimic your problem with below fiddle.
http://jsfiddle.net/kr7ttdhq/12/
newElement.onclick = createClickableCells;
del.onclick = delCell;
The above code shows the snippet from the fiddle
During the onclick event of the cell. New cells are created which in turn have the same onclick events as the first cell.
Moreover, a 'close' text cell is inserted by which you can delete the entire row.
Hope this helps

Dynamic Table navigation in JavaScript using mouse and keyoboard

I am using dynamic table creation and I want to create table navigation using keyboard and mouse when the list is populated in the table. Below is the code that is printing the dynamic list in the table and now I want to navigate it.
function validateInputs(dealerresult) {
alert("Hello");
var params = $("#getDealerdetails").serialize();
var url = '<fmt:message key="app.contextPath"/>/channels/getDealerListbyCriteria.htm?channel=1';
$.post(url, params, function (data) {
//alert("Hello");
//alert(data);
var dealerData = data;
var JSONObj = JSON.parse(dealerData).result;
var table = document.getElementById(dealerresult);
var rowCount = table.rows.length;
alert(rowCount);
//var row = table.insertRow(rowCount);
// var cell; = row.insertCell(0);
// cell1.innerHTML="Dealer"
// var cell2 = row.insertCell(1);
// cell2.innerHTML = 'Town'
for (i = 0; i < JSONObj.length; i++) {
var row = table.insertRow(rowCount);
//row.style.className = 'navigateable';
row.insertCell(0).innerHTML = JSONObj[i].bpName;
row.insertCell(1).innerHTML = JSONObj[i].bpTown;
rowCount++;
//alert(JSONObj[i].bpName);
}
});
document.getElementById('popupa').style.display = 'block';
}
You can find which key is pressed by identifying the keyCodes of the key pressed. Take a look at the following snippet of code which is being currently used by me to navigate through a jqgrid using up/down arrow keys.
$(document).keypress(function(e){
e.preventDefault(); // so that the default event for the key, which is to
// scroll is disabled.
if(e.keyCode == 40) { // down arrow key
// write code to get the row or highlight it using jquery and css
}
if(e.keyCode == 38) { // up arrow key
// write code to get the row or highlight it using jquery css
}
});
Also if you intend to just highlight the row and show it always in the screen then you can write appropriate code to do that. Suppose the row is not visible then look into scrollIntoView() which can show an element on the screen.
Hope this is what you are looking for. If you find a better answer please post it here so that I can change my approach. :)

Categories

Resources