Gilbrant Roychan
Gilbrant Roychan

Reputation: 1

How to change the image components according to the screen size?

I have a study case:

I have an image wrapped in an intro div for the desktop size like this:

<div class="intro">
            <img id="gambar" src="assets/images/image-intro-desktop.jpg" alt="">
        </div>

then when entering the mobile file size the img tag will change to:

<img id="gambar" src="assets/images/image-intro-mobile.jpg" alt="">

So the question is how do I change the component, what js code should I use??

Upvotes: 0

Views: 52

Answers (3)

Nick
Nick

Reputation: 77

You asked for Javascript code so:

Maybe you can run this in a window.onload. Depends on what you want.

if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
  // returns true if its a mobile
  // change src here
  document.getElementById('gambar').src = "assets/images/image-intro-mobile.jpg";
}else{
  // returns false if it isn't
}

Upvotes: 0

vmank
vmank

Reputation: 784

You would need to add two event listeners for the resize and load events, check the window width if it's smaller than your desired breakpoint to change the image source. Otherwise reset the source back to the original.

document.addEventListener( 'resize', changeImageSrc() );
document.addEventListener( 'load', changeImageSrc() );


function changeImageSrc() {
  var init_img_src = document.getElementById('gambar').src;
  
  // Change 600 to your breakpoint
  if( window.innerWidth < 600 ) {
    document.getElementById('gambar').src = 'https://via.placeholder.com/250';
  } else {
    document.getElementById('gambar').src = init_img_src;
  }
}
<div class="intro">
  <img id="gambar" src="https://via.placeholder.com/550" alt="">
</div>

Upvotes: 1

Nuno Dias
Nuno Dias

Reputation: 126

You can do this using css

<style>
  .intro{
    content:url("assets/images/image-intro-desktop.jpg");
  }

  @media only screen and (max-width: 600px) {
    .intro{
       content:url("assets/images/image-intro-mobile.jpg");
    }
  }
  </style>

  <img class="intro"/>

Upvotes: 1

Related Questions