How to display an image within a widget?

Displaying an image within a widget is not that big a deal: just add the proper HTML tag (<img src=”” alt=”” />), fill it with an absolute URL to the image to display, and you're done. You may style it with CSS through classes, work with like any normal image, anything…

What could seem difficult, though, is how to deal with images that are sensibly bigger than the widget itself. It is in fact not difficult at all.

Through the UWA widget object, you can access many methods (see ”Using JavaScript and Ajax in a UWA widget”), among which is getDimensions() for HTML elements. You can then get the widget's width, and put it in the img tag's width attribute.

Here is how you could use it, in the style of the APOD sample widget:

var imageWidth = widget.body.getDimensions().width;
var imageFile = 'image007.jpg';
var imageDesc = 'A description';
 
var contentHtml = '';
contentHtml += '<a href="http://example.org/images/" 
  target="_blank" title="' + imageDesc + '">';
contentHtml += '<img src="http://example.org/images/'
  + imageFile +  '" width="' + imageWidth  + '" alt="' 
  + imageDesc + '" />';
contentHtml += '</a>';
 
widget.setBody(contentHtml);
 
// sets the widget title. 
// use <em> to template the subtitle, in order for it to get styled by the UWA UI.
widget.setTitle(imageDesc + "- <em>Service Name</em>");

You could also get the image through a local script, which would test first if the file needs to be resized, and then apply the needed dimension.

Since user can now resize their columns in Netvibes, using getDimensions().width has the added advantage to adapt the size of the image to that of the widget:

widget.onResize = function() {
  var image = widget.body.getElementsByTagName("img")[0];
  if (image) {
    image.width = widget.body.getDimensions().width;
    }
  }