I am trying to write a code to a HTML page, in which there is a table of values. I want that a click on any row of the table changes the background color of another element, basically just a box, to highlight it amongst the other boxes. I am relatively new to JS, HTML, CSS, so I haven’t quite made it work.
Rn, i got the click on the row to actually change the color of the box, but with a couple problems. Only the first row of the table works, and it doesn’t change back to the original after i "unclick" it.
Anyone can help? Thanks in advance.
the code i have at the moment is this:
<style>
#row{
position:relative;
}
#sensor{
width:30px;
height:22px;
margin: 0 0 -15px 0;
background-size:100%;
background: white;
background-repeat:no-repeat;
overflow:hidden;
border: 1px solid black;
position:absolute;
left: 70px; top: 100px;
z-index: 1;
}
#sensor.clicked {background: greenyellow}
</style>
<div>
<table>
<tbody>
<tr id="row">
<td> various table rows </td>
</tr>
</tbody>
</table>
</div>
$('#row').on('click', function () {
$("#sensor").addClass('clicked');
});
<div>
<div id="sensor">CON</div>
</div>
2
Answers
If you are learning to code and manipulate the DOM try not to rely on jQuery. Here’s the outline of a pure JavaScript solution which will work in all modern web browsers.
The document.getElementById method gets a reference to the HTML table element using its unique id.
The addEventListener method is used to attach a handler function to process
click
events on the table.Within the handler function there is a guard to check if the element click has the
sensor
class before toggling theclicked
class on the element.If you insist on using jQuery, the following snippet will work in place of the JavaScript code.
The following uses a delegated event listener, bound to the parent table (
id='womble'
), to interceptclick
events that happen within it and it’s child elements.Because of event propagation you can inspect the
event
to find the element upon which the event was initially triggered and deduce whether it is a table row or table cell etc. From there you can easily toggle the desired change of class for the element with IDsensor
If the table has more than one row you would need to use a
class='row'
attribute instead of the ID or, alternatively, use adataset
attribute such asdata-id='row'
which is permissable.Notice that clicking on the same cell twice will toggle both the sensor class and the cell itself whereas clicking on separate cells will only toggle the sensor class.