1

I'm building a simple HTML page in AMP and I encountered a problem. I want to change the img src through JavaScript and it does not seem to work.

HTML:

<amp-img id="logo-cat" src="http/images.." alt="logo-category"

JavaScript:

var logoimg = document.getElementById("logo-cat"); 


    logoimg.src = "https://cdn.vox-cdn.com/uploads/chorus_asset/file/8597673/ph_1_color_black_moon_copy_1000x1000.png";

This does not seem to work.

yuriy636
  • 11,171
  • 5
  • 37
  • 42
subt
  • 29
  • 1
  • 7

2 Answers2

6

Javascript is not supported in AMP. Use amp-bind to to update [src] attribute.

<amp-state id="images">
  <script type="application/json">
    {
      "imageUrl_1": "http://via.placeholder.com/350x350",
      "imageUrl_2": "http://via.placeholder.com/250x250",
      "imageUrl_3": "http://via.placeholder.com/150x150"
    }
  </script>
</amp-state>
<script async src="https://cdn.ampproject.org/v0.js"></script>
<script async custom-element="amp-bind" src="https://cdn.ampproject.org/v0/amp-bind-0.1.js"></script>
    
<button on="tap:AMP.setState({imageUrl: images.imageUrl_1})">Image 1</button>
<button on="tap:AMP.setState({imageUrl: images.imageUrl_2})">Image 2</button>
<button on="tap:AMP.setState({imageUrl: images.imageUrl_3})">Image 3</button>

<amp-img id="amp-img"
  src="http://via.placeholder.com/350x350"
  layout="responsive"
  width="350"
  height="350"
  [src]="imageUrl ? imageUrl : images.imageUrl_1">
</amp-img>
adnanyousafch
  • 1,172
  • 9
  • 26
  • Are amp scripts (https://cdn.ampproject.org/v0.js and the custom element) usually put in ``? – stealththeninja Nov 03 '17 at 04:13
  • 1
    Scripts allow you to add a certain functionality which you can use through tags/attributes. For example check out the amp-bind example https://ampbyexample.com/components/amp-bind. Basically, after including amp-bind in head (``) you have the power to use local variables in `[src]` or `[value]`. – adnanyousafch Nov 03 '17 at 04:33
  • i want to load a different images depending on the URL, not loading the Images as an event occur in the HTML. i used JS to split from the URL: for exmaple: https://test.com?=cat and i got the input CAT, now i want before the page reload to inject it to the HTML to show a picture of a cat how can achieve this? – subt Nov 05 '17 at 15:30
  • @subt You only mentioned image URL as a string in Question. can you post the javascript that is extracting and creating image name? – adnanyousafch Nov 06 '17 at 02:22
  • @adnanyousafch, I tried this code to implement AMP for email, to change image on button click. But its not working on button click when I validate the code in AMP validator is says I cant use [src] in amp-image tag. I have included amp-bind script. What could be the issue? – Rajesh Bhat Oct 05 '21 at 15:41
0

AMP HTML Specification:

Author-written Javascript is not allowed in AMP-HTML.

Additional reference from this SO post.

ReyAnthonyRenacia
  • 17,219
  • 5
  • 37
  • 56