How can I add Alt Text to an image?

Here’s a dependency you can use… that has an image component with an alt text option…
https://anvil.works/build#clone:4QGV5KUAC3GBQAPH=OJ6CC37KJOJIABNGUMI7FALN

It has two properties - source and alt. You can set these in properties or in code.

self.image_alt_1.source = "_/theme/bad.png"
self.image_alt_1.alt = "Bad"

I think it’s what you’re after…

Screen Shot 2020-02-22 at 16.51.01

To use it as a dependency clone the app. (Rename it to ImageAltComponent)
Then in your Main App go to

  • :gear: settings
  • :jigsaw: dependencies
  • add a dependency - ImageAltComponent


For those interested here’s the code for the component (no javascript required and much more in an anvil style :innocent:):

class ImageAlt(ImageAltTemplate):
  _source = ''
  _alt = ''
  
  def __init__(self, **properties):
    self.init_components(self, **properties)
    
  @property
  def source(self):
    return self._source
  
  @source.setter
  def source(self, value):
    self._source = value
    self.html = f'<img src="{self._source}" alt="{self._alt}" style="max-width: 100%; display: block; margin: auto;" >'
    
  @property
  def alt(self):
    return self._alt
  
  @alt.setter
  def alt(self, value):
    self._alt = value
    self.html = f'<img src="{self._source}" alt="{self._alt}" style="max-width: 100%; display: block; margin: auto;" >'
    

The initial custom html is as above, but with a placeholder image so that something appears when you add the component into the app design view.

4 Likes