I am trying to set up a virtual photo gallery with a table listing details about each image, such that when the user mouses over an image, the corresponding row in the table is highlighted. I wanted to do this without needing to write a separate function for every image/row pair. I came up with a solution and was one step away from success when I hit a snag. Explanation is as follows:
Image HTML:
<img id="photo1" onmouseover="imgSelectOn(this)" class="img-rounded" src="img/photo1.jpg" alt="">
<img id="photo2" onmouseover="imgSelectOn(this)" class="img-rounded" src="img/photo2.jpg" alt="">
Table row HTML:
<tr id="photo1row"><td>2015</td><td>photo1.jpg</td><td>Photo 1</td>
<tr id="photo2row"><td>2009</td><td>photo2.jpg</td><td>Photo 2</td>
The idea was that the script would select the id of the image on mouseover (e.g. "photo1") and add "row" to the end (e.g. "photo1row") - now you have the id of the correct table row, allowing us to execute a function to change the background styling.
JavaScript:
function imgSelectOn(element) {
document.getElementById(" " + element.id + "row").style = "background: yellow";
}
When I run this I get the console error
"Uncaught TypeError: document.getElementById(...) is null".
I know that this error can come up when you don't put quotes around the value in the brackets [e.g. document.getElementById("photo1row") ], so I added yet another pair of quotes within the brackets...
document.getElementById(" " " + element.id + "row" ").style = "background: yellow";
Now I get the console error
"Uncaught ReferenceError: imgSelectOn is not defined".
I played around with different arrangements of quotes / apostrophes ( " / ' ) to try to make this work, without success; the browser isn't able to make sense of it. Is this the result of a simple typo or am I using entirely the wrong logic here?
Ben