script : only one image tag show with multiple src (one is desktop and the second is mobile)
Thu Mar 07 2024 10:30:09 GMT+0000 (Coordinated Universal Time)
Saved by
@mubashir_aziz
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>
content_copyCOPY
70 30 customized module new horizon academy code . This code will add image in desktop and mobile according to device.
Comments