html
<img class="dynamicImage" src="" alt="Dynamic 59 Image">
javascript
<script>
document.addEventListener("DOMContentLoaded", function () {
var pageWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
console.log(pageWidth);
// Check the page width and set the image source accordingly
var imgSource = (pageWidth > 991) ? "<?php echo $img_url; ?>" : "<?php echo $img_url_mobile; ?>";
console.log(imgSource);
console.log("test image url");
// Set the image source dynamically
console.log(document.getElementsByClassName("dynamicImage")[0]);
var img_tag_nmb = document.getElementsByClassName("dynamicImage");
for (let i = 0; i < img_tag_nmb.length; i++) {
console.log(i);
document.getElementsByClassName("dynamicImage")[i].src = imgSource;
}
});
</script>
<-- without console.log -->
<script>
document.addEventListener("DOMContentLoaded", function () {
var pageWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var imgSource = (pageWidth > 991) ? "<?php echo $img_url; ?>" : "<?php echo $img_url_mobile; ?>";
var img_tag_nmb = document.getElementsByClassName("dynamicImage");
for (let i = 0; i < img_tag_nmb.length; i++) {
document.getElementsByClassName("dynamicImage")[i].src = imgSource;
}
});
</script>
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter