0

How to replace image URL and size when screen size is less than 740px using javascript or jquery?

For example, I want to show one logo for mobile and a different one for large screens.

<p>Large Screens:</p>
<div class="header__logo d-flex align-items-center w-100" style="max-width: 200px;">
    
  <img style="max-width: 200px;" class="rimage__img rimage__img--fade-in lazyload loaded" data-master="//cdn.shopify.com/s/files/1.png"  data-scale="2" itemprop="logo" alt="Crafty" srcset="//cdn.shopify.com/s/files/1.png, //cdn.shopify.com/s/files/1.png" data-was-processed="true">
</div>

<p>Small screen</p>
<div class="header__logo d-flex align-items-center w-100" style="max-width: 200px;">
  <img style="max-width: 40px;" class="rimage__img rimage__img--fade-in lazyload loaded" data-master="//cdn.shopify.com/s/files/2.png"  data-scale="2" itemprop="logo" alt="Crafty" srcset="//cdn.shopify.com/s/files/2.png, //cdn.shopify.com/s/files/2.png" data-was-processed="true">
</div>
SuleymanSah
  • 17,153
  • 5
  • 33
  • 54
Ivan Dan
  • 15
  • 5
  • This link might helpful: https://stackoverflow.com/questions/25482765/bootstrap-change-image-according-to-device/38889308#38889308 – Siddiqui Noor Nov 15 '19 at 06:54
  • 1
    You might want to read about srcset attribute. MDN llink here https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images – SPS Nov 15 '19 at 11:47

2 Answers2

0

Pseudo code:

    if ($(window).width() < 740) {
       alert('Less than 740');
    }
    else {
       alert('More than 740');
    }

your requirement can achieve by different ways. Simplest is just show/hide the respective img based the window's width

Boobalan
  • 795
  • 1
  • 5
  • 14
0

First you need to avoid the inline styling since it can cause to troubles when styling through stylesheet, not to mention accessibility problems etc.

You can achieve this with css @keyframes, but you ask about javascript so take a look on this SO

And maybe even start with this MDN

Enjoy code!

Edit (working code example using vanilla js):

if (window.innerWidth < 740) { // if screen is less than 740 px
  document.querySelectorAll('.header__logo > img')[0].setAttribute('src', '//cdn.shopify.com/s/files/2.png, //cdn.shopify.com/s/files/2.png');
  document.querySelectorAll('.header__logo > img')[0].style.maxWidth = '40px';
}
<div class="header__logo d-flex align-items-center w-100" style="max-width: 200px;">  
  <img style="max-width: 200px;" class="rimage__img rimage__img--fade-in lazyload loaded" data-master="//cdn.shopify.com/s/files/1.png"  data-scale="2" itemprop="logo" alt="Crafty" src="//cdn.shopify.com/s/files/1.png, //cdn.shopify.com/s/files/1.png" data-was-processed="true">
</div>
A. Meshu
  • 4,053
  • 2
  • 20
  • 34