Reputation: 27
I would like to create an on click button to run a javascript function to generate a grid in the style of a crossword.
I have written some javascript to create the grid and I have made the button with the onclick function, but I am unable to get the button to run the script.
I'm sure the solution is glaringly obvious but I'm new to coding so any and all help would be appreciated!
<html>
<body>
<!--<button onclick="generateGrid()">Click to generate crossword grid</button>-->
<div id="crosswordGrid" align="center"></div>
</body>
</html>
function generateGrid () {
var crosswordGrid = document.getElementById("crosswordGrid");
for (var r = 0; r < rows; r++) {
var row = crosswordGrid.appendChild(document.createElement("div"));
for (var c = 0; c < cols; c++) {
row.appendChild(document.createElement("span"));
}
}
const gridSize = 7;
var rows = gridSize;
var cols = gridSize;
}
This is what my current code looks like; http://jsfiddle.net/YEJ9A/97/
Upvotes: 2
Views: 8464
Reputation: 11
Try to use "addEventListener" instead of "onclick"
here is my answer
document.getElementById ("btn").addEventListener("click", function() {
generateGrid(7);
} , false);
function generateGrid(gridSize) {
var rows = gridSize;
var cols = gridSize;
var crosswordGrid = document.getElementById("crosswordGrid");
for (var r = 0; r < rows; r++) {
var row = crosswordGrid.appendChild(document.createElement("div"));
for (var c = 0; c < cols; c++) {
row.appendChild(document.createElement("span"));
}
}
}
#crosswordGrid div {
line-height: 1px;
}
#crosswordGrid span {
display: inline-block;
width: 28px;
height: 28px;
border: 1px solid black;
}
#crosswordGrid div:nth-child(even) span:nth-child(even) {
background-color: black;
}
#crosswordGrid div:nth-child(odd) span:nth-child(odd) {
background-color: white;
}
<html>
<body>
<button id="btn">Click to generate crossword grid</button>
<div id="crosswordGrid" align="center"></div>
</body>
</html>
Upvotes: 1
Reputation: 550
So I think you were mostly the way there. I moved the values you were assigning at the bottom of the file into the default value of the function. See the corrections below.
Also updated on fiddle. https://jsfiddle.net/r8aLbakr/1/
function generateGrid (gridSize = 7, rows = 7, cols = 7, crosswordGrid) {
var crosswordGrid = document.getElementById("crosswordGrid");
for (var r = 0; r < rows; r++) {
var row = crosswordGrid.appendChild(document.createElement("div"));
for (var c = 0; c < cols; c++) {
row.appendChild(document.createElement("span"));
}
}
}
#crosswordGrid div {
line-height: 1px;
}
#crosswordGrid span {
display: inline-block;
width: 28px;
height: 28px;
border: 1px solid black;
}
#crosswordGrid div:nth-child(even) span:nth-child(even) {
background-color: black;
}
#crosswordGrid div:nth-child(odd) span:nth-child(odd) {
background-color: white;
}
<html>
<body>
<button onclick="generateGrid()">Click to generate crossword grid</button>
<div id="crosswordGrid" align="center"></div>
</body>
</html>
Upvotes: 1