Javascript .addEventListener "mouseenter" For A Class
first time poster, long time lurker here. I have a table in HTML that has the ID SalesList and I want the cells within it to be highlighted green when the mouse is over it. The fol
Solution 1:
The onmouseover event occurs when the mouse pointer is moved onto an element, or onto one of its children.
The onmouseenter event occurs when the mouse pointer is moved onto an element.
So, change this :
theParent.addEventListener("mouseenter", doSomething, false);
to :
theParent.addEventListener("mouseover", doSomething, false);
Solution 2:
Please do not use JavaScript for that. This can and should be used with css instead. Simply apply the :hover
pseudoselector.
td:hover {
color: green;
}
<table id="sales-list">
<tr>
<td>Pineapple</td>
<td>$3.00 </td>
</tr>
<tr>
<td>Bread</td>
<td>$2.00</td>
</tr>
</table>
Let's compare this to what we'd have to do in JavaScript.
var cells = document.querySelectorAll("td");
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener("mouseover", function() {
this.style.color = "green";
});
cells[i].addEventListener("mouseout", function() {
this.style.color = "black";
});
}
<table id="sales-list">
<tr>
<td>Pineapple</td>
<td>Bread </td>
</tr>
<tr>
<td>$3.00</td>
<td>$2.00</td>
</tr>
</table>
In JavaScript, you'd have to query a list of td
elements, loop through all of them and for each of them add two event listeners. This is about 10 lines of extra code we don't need.
TLDR: Best to use CSS for this.
Post a Comment for "Javascript .addEventListener "mouseenter" For A Class"