sojutyp sojutyp - 1 year ago 61
HTML Question

Changing <td> background-color when hovering over an image

I am looking for the functionality described in the topic. When the user hovers over an image (id="sie"), the background of an table cell (id="sein_img") should change. I tried using this code but I am not sure why it doesn't work. Help would be very much appreciated!

<script type="text/javascript">
document.getElementById("sein_img").onmouseover = function() {
document.getElementById("sie").style.backgroundColor = "red";

<td id="sie" style="background-color: #f3f5f7;">&nbsp;sie</td>

<img id="sein_img" src="images/stories/bullet_white.png" />

Answer Source

Your script works perfectly fine, but only if you execute the <script> after the initialization of the affected HTML tags (in your case the <div> with the id sein_img). The element is not yet available, so the mouseover listener is not set to the element (the element you get with document.getElementById() is undefined.

So, to resolve your problem you can choose between those 2 options:

  1. Move your <script> tag to the bottom of the page or at least after the last element you want to set a listener to.
  2. Wait for the document to be ready before setting a listener to an element. You can e.g. do that with jQuery ($(document).ready(function() { ... });)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download