Reputation: 29
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.
Upvotes: 1
Views: 2855
Reputation: 1172
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>
Upvotes: 6
Reputation: 17613
Author-written Javascript is not allowed in AMP-HTML.
Additional reference from this SO post.
Upvotes: 0