Artificial Crayon Artificial Crayon - 7 months ago 12
HTML Question

onClick colour palette

I am trying to make a colour pallet so that I press on the colour, then press on an empty space in a table and the space will change to the colour I've selected. This is through using images.
I'm really new to JavaScript so I'm struggling to understand how the onClick is working and if my functions are doing what they should be.

function GetColour(){
colBlue = document.getElementById("Blue");
colRed = document.getElementById("Red");
colYellow = document.getElementById("Yellow");
colGreen = document.getElementById("Green");
colOrange = document.getElementById("Orange");
colBlack = document.getElementById("Black");
colWhite = document.getElementById("White");
colBrown = document.getElementById("Brown");
}

function CellClicked(cell){
document.getElementById("board").setAttribute(GetColour(), id)
}


Here is my colour pallet (they're set into two tables for layout so I'll just show one for this post. This is outside the script tags.

<div id="board" onlClick="GetColour()">
<table>
<tr height=30>
<td id=Blue><img type='button' src='Blue.gif' onclick='GetColour()'></td>
<td id=Red><img type='button' src='Red.gif' onclick='GetColour()'></td>
<td id=Yellow><img type='button' src='Yellow.gif' onclick='GetColour()'></td>
<td id=Green><img type='button' src='Green.gif' onclick='GetColour()'></td>
</tr>


And here is my row of 4 'spaces' to put these colours.

<TR>
<TD>
<IMG src="transparent.gif" alt="empty hole" onclick="CellClicked(1)">
<IMG src="transparent.gif" alt="empty hole" onclick="CellClicked(2)">
<IMG src="transparent.gif" alt="empty hole" onclick="CellClicked(3)">
<IMG src="transparent.gif" alt="empty hole" onclick="CellClicked(4)">
</TD>


I hope I've asked this question to an understandable manner, When I use Chrome's console, clicking a colour shows nothing (assuming and hoping it's worked. but then pressing on an empty space to place the colour I get an errors saying "Uncaught ReferenceError: id is not defined" referring to the id in the CellClicked() function.

Answer

Well, too many errors in your js. I don't know where to start with. I have to give u a new method: 1. Change all your GetColour() to GetColour(this) 2. Change all your CellClicked() to CellClicked(this) 3. Add the code in your js

var colorArr = [];
function GetColour(e) {
    colorArr.push(e.src);
}
function CellClicked(e) {
    var color = colorArr.pop();
    e.setAttribute("src", color);
}

Looks like this Other small errors for u to find out.