Escaping is the (biggest) problem (as Daniel Gimenez already identified while I was still typing this answer), but do read the edit below!
Your first string would render the following (obviously) invalid HTML (note the nested '
characters, the closing tag and the lack of a src
attribute):
<img class='thumb' style='background-image: url('images/video_icons/moo.png');'></img>
I'll try to explain the escaping in simple steps (so future readers can do this on their own).
But first, an image is a void
element, meaning it has no closing-tag.
So imagine you want this as your resulting html:
<img class='thumb' style='background-image: url("images/video_icons/moo.png");'>
then in javascript you'd choose the "
character to wrap your string; that way there are only 2 (instead of 4) characters to escape.
Note that whilst you can generally leave out the quotes in the css url, one must know the exceptions when this doesn't work, so it is safest to use the quotes, then you don't need to remember anything (making it an error-proof and consistent coding style).
Now let's wrap and escape that string (for javascript):
"<img class='thumb' style='background-image: url(\"images/video_icons/moo.png\");'>"
Finally, you want javascript to provide the variable 'moo.png' string.
For clarity, I'll first replace it with a ?
.
"<img class='thumb' style='background-image: url(\"images/video_icons/" + ? + "\");'>"
Now let's replace that ?
with your videos[i]["Thumbnail Title"]
(It does not matter in this case if you used '
or "
to call your Thumbnail Title
property):
"<img class='thumb' style='background-image: url(\"images/video_icons/" + videos[i]["Thumbnail Title"] + "\");'>"
That is it! Ok, you'd need to append that string to your table
var: table += ? ;
:
table += "<img class='thumb' style='background-image: url(\"images/video_icons/" + videos[i]["Thumbnail Title"] + "\");'>";
Hope this helps in the future!
EDIT:
Stefan Koenen has a good point about the image's missing src
attribute.
In HTML4.01 spec the src
(and alt
) are required
. In the HTML5 proposal, only the src
is mandatory (and must be valid) whilst the alt
attribute is debatable.
Apart from these rues, just for the sake of cross-browser-compatibility, authors have opted for 1 of the following 2 common solutions:
- Use a
div
(instead of an image, seems most appropriate solution in this case)
- Set the
src
attribute of the image to a transparent gif of 1*1px.
(Also 'costs' extra image to be loaded)
Here is an excellent rule of thumb for making such (design-)decisions about the usage of images.