<script type="text/javascript">
$(window).resize(function(){
var width = $(window).width();
if (width < 361) {
$(".infograph-image").attr("src","/images/infographicHowMobile.png");
}
});
</script>
I wish to change the image source of a given image, based on the viewport width size.
If the viewport width size is 360 or less, change to a mobile version of the image.
I have two simple questions:
1)
How can we do both: a) detect windows resize AND document ready ?
This, I believe I got:
I need to change that into a function.
Then call it on load;
checkResponsive();
Then bind a event listener:
$(window).resize(checkResponsive);
2)
We have several images that need to have a mobile version, should this be converted to a function ? Or several ifs may work ?
Can you please give me a kick-off start on those two questions please.
Create a seperate function and call them on both events.
So, for example, create the function mobileImg() like this:
And then call this on both events.
You can then call the
mobileImgmethod as much as you want and with whatever params.If you really want to make it clean, also add a check if the passed element and image exist at all and use fallbacks where needed.