How to make button.onClick not run at start - javascript

I am confused at to why my function executes before the start button is pressed. I looked around and they said the onclick will run at the start if you don't but the code to be executed when the button is clicked in a function. But mine is a function... This code is supposed to create 4 buttons when the start button is pressed. But right now the 4 buttons appear right away.
EDIT: Here is the full code.
var log = document.getElementById("Log");
log.addEventListener("click", login); // Runs the Login Function
var email;
var password;
// Makes an alert to test input values.
function login() {
form = document.getElementById("form");
var text = "E-Mail: " + form.elements[0].value + " Password: " + form.elements[1].value;
alert (text);
}
// Testing Function
function helloWorld() {
alert ("Hello World");
}
//create the snake
function createSnake() {
var bodyLength = 5; //snake length
var body = []; //snake body
var head = [10, 10]; //snake head starting position;
// create the variables to edit for the body positions loop
var row = head[0];
var col = head[1];
// set the snake body positions
for (var i=0;i<bodyLength; i++) {
body[body.length] = [row, col];
var cord = row + "_" + col;
// Set the head Green
if (i == 0) { document.getElementById(cord).style.backgroundColor = 'green';
}
// Set the Body blue
else {document.getElementById(cord).style.backgroundColor = 'blue';}
row++;
}
}
var snakeBool = false; //Bool to test if the snake game has been pressed.
// Create a table function. Creates a gray table for Snake.
function createTable() {
if (!snakeBool) {
// create a table of data
//target the activity div
var activity = document.getElementById("activity");
//create table
var tbl = document.createElement("table");
//table styles
tbl.style.borderCollapse = "collapse";
tbl.style.marginLeft = '12.5px';
//create size var
//var size = '5px';
//set the row and column numbers
var tr_num = 30;
var td_num = 25;
//start the loops for creating rows and columns
for (var i = 0; i < tr_num; i++) {
var tr = document.createElement("tr"); // create row
//tr style
tr.style.height = '7px';
for (var j = 0; j < td_num; j++) { //start loop for creating the td
var td = document.createElement("td"); //create td
td.style.width = '5px';
if (i == 0 || i == (tr_num-1) || j == 0 || j == (td_num-1)) {
td.style.backgroundColor = "white";
}
else {
td.style.backgroundColor = "gray";
}
td.id = i + "_" + j; //set id to td
//td.appendChild("data"); //append data to td
tr.appendChild(td); //append td to row
}
tbl.appendChild(tr); //append tr to the table
}
activity.appendChild(tbl); //append the table to activity div
createSnake(); //Creates the snake body.
snakeBool = true; //Sets the Snake Bool to true since game has been created.
//create Start button
var b1 = document.createElement("input");
b1.type = "button";
b1.value = "Start";
b1.onClick = startGame;
activity.appendChild(b1);
} // end of if Function
}
function startGame() {
createButtons();
}
function createButtons() {
var b1 = document.createElement("input");
b1.type = "button";
b1.value = "Up";
//b1.onClick = func
activity.appendChild(b1);
var b2 = document.createElement("input");
b2.type = "button";
b2.value = "Down";
//b1.onClick = func
activity.appendChild(b2);
var b3 = document.createElement("input");
b3.type = "button";
b3.value = "Left";
//b1.onClick = func
activity.appendChild(b3);
var b4 = document.createElement("input");
b4.type = "button";
b4.value = "Right";
//b1.onClick = func
activity.appendChild(b4);
}
// when button is pressed, do createTable function
document.getElementById("gamesButton").addEventListener("click", createTable);

Using the brackets, you’re immediately invoking the startGame function. Its return value is then assigned to the onClick property.
You most likely want to assign the function itself, so it’s executed when the onClick event fires. To do so, change this
b1.onClick = startGame();
to this
b1.onClick = startGame;

Related

How can I make a tableRow tappable? I've watched online but it didn't work

I would like to open a new page when I tap a cell (TR) in Javascript. I've searched a lot of tutorials online but it doesn't work as well. I hope that someone could help me. Thanks.
Here is my code:
function generateTableBirre()
{
//Build an array containing Customer records.
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
//Create a HTML Table element.
var table = document.createElement("Table");
table.border = "1";
table.className = "Birre";
table.cellSpacing = 20;
//Add the data rows.
for (var i = 0; i < birre.length; i++) {
row = table.insertRow(-1);
var cell = row.insertCell(-1);
var generalDiv = document.createElement("div");
generalDiv.className = "General-Div";
// Create an a tag
var a = document.createElement('a');
a.href = "Antipasti.html";
a.appendChild(cell);
cell.appendChild(a);
var div = document.createElement("div");
div.id = "div-nome-prezzo-birre";
var nameprezzo = document.createElement("p");
nameprezzo.innerHTML = birre[i] + ' - ' + price[i];
nameprezzo.id = "nome-prezzo-birre";
div.appendChild(nameprezzo);
var image = document.createElement("img");
image.src = "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png"
image.id = "image-bibite";
generalDiv.appendChild(div);
generalDiv.appendChild(image);
cell.appendChild(generalDiv);
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
If you would like to show the table, here is the image:
In the Javascript below the table is created with 2 cells per row. In the first cell you'll find a div with a text paragraph. In the second cell you'll find a div with anchor and image.
Important: an id must be unique so I had to remove lines where duplicate id's were created. If you want to use extra selectors then you can use classList.add("...")
In the css you can style the image width, font, color, etc. For example #dvTable img { max-width: 250px; height: auto; border: 0; }
function generateTableBirre() {
// array containing records
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
// create table
var table = document.createElement('table');
table.classList.add("Birre");
table.setAttribute('border', '1');
table.setAttribute('cellspacing', '20');
// loop through the array and create rows
for (var i = 0; i < birre.length; i++) {
var row = document.createElement('tr');
// loop from 0 to 1 to create two cells on each row
for (var j = 0; j < 2; j++) {
var cell = document.createElement('td');
// give each cell a inner div
var div = document.createElement("div");
div.classList.add("General-Div");
cell.appendChild(div);
// different content in cell 0 and cell 1
if (j == 0) {
// cell 0 contains paragraph
var par = document.createElement("p");
par.innerHTML = birre[i] + ' - ' + price[i];
div.appendChild(par);
} else {
// cell 1 contains image in an anchor
var anch = document.createElement('a');
anch.setAttribute('href', 'Antipasti.html');
div.appendChild(anch);
var img = document.createElement("img");
img.setAttribute('src', 'https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png');
anch.appendChild(img);
}
row.appendChild(cell);
}
table.appendChild(row);
}
// append table in id=dvTable
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
generateTableBirre();
<div id="dvTable">
</div>
try this,
function generateTableBirre() {
//Build an array containing Customer records.
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
//Create a HTML Table element.
var table = document.createElement("table");
table.border = "1";
table.className = "Birre";
table.cellSpacing = 20;
//Add the data rows.
for (var i = 0; i < birre.length; i++) {
//var row = table.insertRow(-1);
//var cell = row.insertCell(-1);
var row = document.createElement("tr");
table.appendChild(row);
var cell = document.createElement("td");
var generalDiv = document.createElement("div");
generalDiv.className = "General-Div";
// Create an a tag
var a = document.createElement('a');
a.href = "Antipasti.html";
a.appendChild(cell);
row.appendChild(a);
var div = document.createElement("div");
div.id = "div-nome-prezzo-birre";
var nameprezzo = document.createElement("p");
nameprezzo.innerHTML = birre[i] + ' - ' + price[i];
nameprezzo.id = "nome-prezzo-birre";
div.appendChild(nameprezzo);
var image = document.createElement("img");
image.src = "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png"
image.id = "image-bibite";
generalDiv.appendChild(div);
generalDiv.appendChild(image);
cell.appendChild(generalDiv);
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}

Parent node undefined in button creation

I'm developing a test build for my project, which includes a lot of data manipulation. I have two buttons inline at the end of the rows, one for editing, and one for committing the changes made.
function editRow(btn) {
var row = btn.parentNode.parentNode;
row.contentEditable = "true";
row.focus();
}
function addRow(tableID, numberOfCells) {
var tbl = document.getElementById(tableID);
//create rows
var newRow = tbl.insertRow(-1);
var i;
for (i = 0; i < numberOfCells; i++) {
newRow.insertCell(0);
}
//assignbuttons
var lastcell = newRow.cells[numberOfCells - 1];
addEditButton(lastcell);
addCommitButton(lastcell);
}
function addEditButton(context) {
var button = document.createElement("input");
button.type = "button";
button.value = "Edit";
button.onclick = editRow(this);
context.appendChild(button);
}
The user will press the new row button, and then an empty row will appear along with the two buttons.
I am getting the error:
Uncaught TypeError: Cannot read property 'parentNode' of undefined
at editRow (js.js:97)
at addEditButton (js.js:123)
at addRow (js.js:115)
at HTMLButtonElement.onclick (index.html:36)
There are 2 problems I can see.
button.onclick = editRow(this); the this would result in undefined (in strict mode) in that scope. You can probably fix this by sending in the button element
button.onclick = editRow(button);
More reading on this in a function scope
Also you are not creating a row with a td element to place the button in. So btn.parentNode.parentNode is not the row element as you are expecting
Try this
function editRow(btn) {
var row = btn.parentNode.parentNode;
row.contentEditable = "true";
row.focus();
}
function addRow(tableID, numberOfCells) {
var tbl = document.getElementById(tableID);
//create rows
var newRow = tbl.insertRow(-1);
var i;
for (i = 0; i < numberOfCells; i++) {
newRow.insertCell(0);
}
//assignbuttons
var lastcell = newRow.cells[numberOfCells - 1];
addEditButton(lastcell);
//addCommitButton(lastcell);
}
function addEditButton(context) {
var row = document.createElement("row");
var td = document.createElement("td");
var button = document.createElement("input");
button.type = "button";
button.value = "Edit";
td.appendChild(button);
row.appendChild(td);
context.appendChild(row);
button.onclick = editRow(button);
}
addRow("myTable", 2)
<table id="myTable">
</table>
function addRow(tableID, numberOfCells) {
var tbl = document.getElementById(tableID);
var tableHTML = $("#" + tableID).html();
if(numberOfCells === 5) {
$("#" + tableID).html(tableHTML + "<tr id=\"bikeTableBike_new\"><td>-</td><td>-</td><td>-</td><td>-</td><td><button id=\"editBikeButton\" class=\"tableButtons\" onclick=\"editRow(this)\"><img src=\"images/edit.png\"/></button><button id=\"deleteBikeButton\" class=\"tableButtons\" onclick=\"commitRow(this)\"><img src=\"images/commit.png\"/></button></td></tr>");
}
if(numberOfCells === 4) {
$("#" + tableID).html(tableHTML + "<tr id=\"bikeTableBike_new\"><td>-</td><td>-</td><td>-</td><td><button id=\"editBikeButton\" class=\"tableButtons\" onclick=\"editRow(this)\"><img src=\"images/edit.png\"/></button><button id=\"deleteBikeButton\" class=\"tableButtons\" onclick=\"commitRow(this)\"><img src=\"images/commit.png\"/></button></td></tr>");
}
if(numberOfCells === 3) {
$("#" + tableID).html(tableHTML + "<tr id=\"bikeTableBike_new\"><td>-</td><td>-</td><td><button id=\"editBikeButton\" class=\"tableButtons\" onclick=\"editRow(this)\"><img src=\"images/edit.png\"/></button><button id=\"deleteBikeButton\" class=\"tableButtons\" onclick=\"commitRow(this)\"><img src=\"images/commit.png\"/></button></td></tr>");
}
}

How to prevent additional table creation

I've been looking for workarounds to ensure that only one table is created. So far the only one i have come up with is to disable the button after it had been pressed. Here is my code:
function bikeData() {
// Select the Table
var tbl = document.getElementById('bikeInnerTable');
var th = document.getElementById('tableHead_B');
var headerText = ["ID", "Bike Status", "Bike Location", "Depot ID"];
// Set number of rows
var rows = 10;
// Set number of columns
var columns = headerText.length;
// create table header
for (var h = 0; h < columns; h++) {
var td = document.createElement("td");
td.innerText = headerText[h];
th.appendChild(td);
}
// create table data
for (var r = 0; r < rows; r++) {
var cellText = ["UNDEFINED", "UNDEFINED", "UNDEFINED", "UNDEFINED"];
// generate ID
x = getRandomNumber(1000, 1);
cellText[0] = x;
// generate Status
x = getStatus();
cellText[1] = x;
// generate Name
x = getLocation();
cellText[2] = x;
// generate depot ID
x = getRandomNumber(1000, 1);
cellText[3] = x;
var tr = document.getElementById("b_row" + r);
for (var c = 0; c < columns; c++)
{
var td = document.createElement("td");
td.innerText = cellText[c];
tr.appendChild(td);
}
}
}
If the button is pressed multiple times then the table is created multiple times. However how can I adapt the code to ensure that it if the table is already present within the div, then it doesn't continue in creating the table additional times.
You can set a flag and then only execute the code when applicable.
let firstTime = true;
function(){
...
if (firstTime) {
firstTime = false;
...
}
}
This is what Javascript variables are for. You can make a variable, then test that against a condition in the function. Let me show you what I mean:
window.timesRan = 0;
function bikeData() {
//Check if the variable is > 1
if (timesRan > 1) {
return false;
}
//code here
//then just add 1 to the variable every time
timesRan += 1;
}
All the best, and I hope my answer works for you :)

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

Javascript to create multiple div elements onclick

I need help with this app. I want the user to choose a name, color and number. When the form is submitted, boxes of the chosen color and number are generated. More boxes can be added and the originals are not erased. Each box has random positioning and a unique id.
Here is my effort: http://jsfiddle.net/christopherpl/gnVj6/
//Invoke functions only after page has fully loaded
window.onload = init;
//Create an array that will be populated by the user generated boxes
var boxes = [];
//Create a global counter variable that keeps track of the number of
//boxes generated
var counter = 0;
//Create a Box constructor function with parameters, to create box objects
//for each box that's generated
function Box(id, name, color, x, y) {
this.id = id;
this.name = name;
this.color = color;
this.x = x;
this.y = y;
}
//Set up the onclick event handler for the generate button input
function init() {
var generateButton = document.getElementById("generateButton");
generateButton.onclick = generate;
var clearButton = document.getElementById("clearButton");
clearButton.onclick = clear;
}
//Get boxes' name from user
function generate() {
var data = document.forms.data;
var textInput = document.getElementById("name");
var name = textInput.value;
if (name == null || name == "") {
alert("Please give your Amazing Box a name");
return;
}
//Get color option from user
var colorSelect = document.getElementById("color");
var colorOption = colorSelect.options[colorSelect.selectedIndex];
var color = colorOption.value;
if (!color) {
alert("Pick a color");
return;
}
//Get number of boxes to be generated from user
var amountArray = data.elements.amount;
for (i = 0; i < amountArray.length; i++) {
if (amountArray[i].checked) {
//Create and append the new <div> element
var div = document.createElement("div");
//Randomly position each <div> element
var x = Math.floor(Math.random() * (scene.offsetWidth-101));
var y = Math.floor(Math.random() * (scene.offsetHeight-101));
//Give each <div> element a unique id
var newId = div;
newId = counter++;
id = newId;
//Add the style, including the background color selected
//by the user.
div.style.left = x + "px";
div.style.top = y + "px";
div.style.backgroundColor = color;
div.setAttribute("class", "box");
scene.appendChild(div);
div.innerHTML = "Box of " + name + "<br />(click me)";
//Create an onclick event displaying the
//details of each box generated
div.onclick = function() {
alert("You clicked on a box with id " + id +
", named Box of " + name + ", whose color is " + color +
" at position " + div.style.top + ", " + div.style.left)
}
//Form reset
data = document.getElementById("data");
data.reset();
}
}
}
//Clear the boxes from scene div
function clear() {
var sceneDivs = document.querySelectorAll("div#scene div");
for (var i = 0; i < sceneDivs.length; i++) {
var scene = document.getElementById("scene");
var cutList = document.getElementsByTagName("div")[1];
scene.removeChild(cutList);
}
}
In your code, when you do this loop:
for (i = 0; i < amountArray.length; i++) {
if (amountArray[i].checked) {
/* make the div */
}
}
You are always just making one box. What you need to do is a second loop, using the value of the radio button as the length of the loop. Something like:
var totalBoxes = 0;
for (i = 0; i < amountArray.length; i++) {
if (amountArray[i].checked) {
totalBoxes = amountArray[i].value;
}
}
for (i = 0; i < totalBoxes; i++) {
/* make the div */
}
That way you will get 5 boxes if the user checked the 5 box, and so on.

Categories