mardi 27 octobre 2020

Java Script | Random image in HTML5 picture tag

Trying to make random images (I have a set of images, all following the pattern "imgN", where "N" is a number from 1 to 9) with HTML5 picture tag. No good till now. This is what I'm trying:

HTML code is:

<picture id="heroimg">
    <source class="rand_webp_srcset" srcset="img1.webp" type="image/webp">
    <source class="rand_jpeg_srcset" srcset="img1.jpg" type="image/jpeg">
    <img class="rand_jpeg_src" src="img1.jpg">
</picture>

Javascript code is:

var randomNum = Math.floor(Math.random() * 9) + 1
document.getElementsByClassName('rand_webp_srcset').srcset = 'img' + randomNum + '.jpg';
document.getElementsByClassName('rand_jpeg_srcset').srcset = 'img' + randomNum + '.jpg';
document.getElementsByClassName('rand_jpeg_src').src = 'img' + randomNum + '.jpg';

Any cue? Thanks.




Aucun commentaire:

Enregistrer un commentaire