Reputation: 5
I am developing a website using php, css and javascript, and I have a question about how to highlight a cell (table) when I click on it? For example I have a table 3x7 and when I click on position 2x2 this position should be highlighted with a color, and if i click again in same cell it goes back, If i click many cell, all of them should be highlighted.
Thanks in advance.
<table border='2' cellpadding='5' align='center'>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>15</td>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
<td>21</td>
</tr>
</tbody>
Upvotes: 0
Views: 915
Reputation: 87251
Simply use event delegation, where you add an addEventListener
to the table
and then use the event target
, here e.target
to detect which td
were clicked.
Then toggle a class on the td
to e.g. highlite them.
Stack snippet
var table = document.querySelector('table');
table.addEventListener('click', function(e) {
e.target.classList.toggle('highlite')
})
td.highlite {
background: yellow
}
<table border='2' cellpadding='5' align='center'>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>15</td>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
<td>21</td>
</tr>
</tbody>
Upvotes: 2
Reputation: 611
let's make it a bit easier with jQuery
css:
.highlight {
background-color: #ffff00;
}
js:
$('td').click(function() {
$(this).toggleClass('highlight');
})
fiddle: https://jsfiddle.net/L5yuc1eg/
Upvotes: -1