I have implemented a custom attribute for the img tag in my code, such as data-tablet
and data-mobil
<div class="myDiv">
<img src="img-1.jpg" data-tablet="img-2.jpg" data-mobil="img-3.jpg">
</div>
My goal is to have the image source change dynamically depending on the screen size, so if the screen is a tablet, the src should change to data-tablet
, and if it's a mobile screen, the src should change to data-mobil
Here is my JavaScript code:
$(document).ready(function(){
$(window).resize(function(){
var tabletSrc = $(".main-carousel img").attr("data-tablet");
var mobilSrc = $(".main-carousel img").attr("data-mobil");
if($(window).width() <=768){
$('img').attr('src',tabletSrc);
}
if($(window).width() <=480 ) {
$('img').attr('src',mobilSrc);
}
});
});
Click here to view my code on Codepen
The question I have is how can I achieve this behavior without any functionality when clicked.
Note: I prefer not to use srcset or CSS for this purpose.