Reputation: 190
I am trying to implement a Web Application which is supposed to let you draw shapes over a grid of pixels. For this purpose, I need to add several event listeners to each table element of my grid. This is what I did so far:
td.addEventListener("click", setpixel);
td.addEventListener("mousedown", function () {
mousedown = true;
})
td.addEventListener("mouseup", function () {
mousedown = false;
})
td.addEventListener("mousemove", function () {
if (mousedown) {
setpixel(?);
}
});
The setPixel() function needs an event passed as parameter:
function setpixel(event) {
var oldColor = this.style.backgroundColor;
var currentColor=document.getElementById("current-color").style.backgroundColor;
if (brushwidth > 1 && brushwidth < 4) {
brushpixel(this.id, offset, currentColor);
}
else if (brushwidth == 4) {
document.body.style.cursor = "url('https://www.wired.com/wp-content/uploads/images_blogs/design/2013/04/Susan-Kare-fill-icon-660x660.jpg')";
floodfill(this.id, currentColor, oldColor);
preview();
}
else {
this.style.backgroundColor = currentColor;
}
preview();
}
Otherwise it cannot function properly. Where do I get the referenced event from?
Linked thread does not work for me here, not sure why, but I tried it out.
Upvotes: 0
Views: 142
Reputation: 1401
add the event to your listening function arguments
td.addEventListener("mousemove", function (e) {
if (mousedown) {
setpixel(e);
}
});
Upvotes: 0
Reputation: 43880
Register the click event to the table and make a condition to which your function will work exclusively with <td>
. Use e.target
to determine which <td>
was actually clicked. Read this article on Event Delegation. Started this answer before your edit so wasn't aware of new additions.
// Reference table#T
var T = document.querySelector('#T');
/* Register the click event on #T
|| setPixel() is the callback
*/
T.addEventListener("click", setPixel);
function setPixel(e) {
/* e.target is the clicked element
|| If the clicked element is a <td>...
*/
var tgt = e.target;
if (tgt.tagName === "TD") {
/* ...if the td does not have a red
|| background then make it red
*/
if (tgt.style.background !== 'red') {
e.target.style.background = 'red';
} else {
/* Otherwise make it black */
e.target.style.background = 'black';
}
}
}
#T {
width: 90%
}
table,
td {
border: 2px solid tomato;
cursor: pointer;
background: black;
}
<table id='T'>
<tbody>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
Upvotes: 1