MEM
MEM

Reputation: 31337

Change image source based on viewport width

<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.

Upvotes: 1

Views: 7656

Answers (1)

Oldskool
Oldskool

Reputation: 34837

Create a seperate function and call them on both events. So, for example, create the function mobileImg() like this:

function mobileImg(targetClass, imageSrc) {
    var width = window.innerWidth; // No need for jQuery here, raw JS can do this

    if(width < 361) {
        $(targetClass).attr("src", imageSrc);
    }
}

And then call this on both events.

$(document).ready(mobileImg(".infograph-image", "/images/infographicHowMobile.png"));
$(window).resize(mobileImg(".infograph-image", "/images/infographicHowMobile.png"));

You can then call the mobileImg method 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.

Upvotes: 1

Related Questions