Reputation: 157
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 following code works:
var theParent = document.querySelector("#SalesList");
theParent.addEventListener("click", doSomething, false);
function doSomething(e) {
if (e.target !== e.currentTarget) {
e.target.style.backgroundColor = "green";
}
e.stopPropagation();
}
I found this code at https://www.kirupa.com/html5/handling_events_for_many_elements.htm
My problem is that when I change
theParent.addEventListener("click", doSomething, false);
to
theParent.addEventListener("mouseenter", doSomething, false);
it does not do what I want it to. I have also tried onmouseenter and many other event types and "click" seems to be the only one working.
Upvotes: 1
Views: 4299
Reputation: 12969
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);
Upvotes: 2
Reputation: 26444
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.
Upvotes: 2