Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change img src with another img attribute on Responsive

I created a attribute for img tag as in the example code like data-tablet, data-mobil

<div class="myDiv">
 <img  src="img-1.jpg" data-tablet="img-2.jpg" data-mobil="img-3.jpg">
</div>

and I want if my screen change for tablet my img src change with data-tablet or my screen is for mobil my src must change with data-mobil

MY JS

$(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 to see my works

question is how can I do that I want if u click you gonna see nothing work

note: I don't want to use srcset or css

like image 201
ani_css Avatar asked Feb 05 '23 11:02

ani_css


1 Answers

Please see this CodePen for a working version.

There were some issues with your code:

  • Both the case for mobile and tablet was executed in the mobile case.
  • $(".main-carousel img") is a collection of images. Instead of that, you probably want to operate on a single image. This can be done with the help of .each().

Here is the relevant code:

$(window).resize(function() {
  if ($(window).width() <= 480) {
    $('img').each(function() {
      $(this).attr('src', $(this).attr('data-mobil'));
    });
  } else if ($(window).width() <= 768) {
    $('img').each(function() {
      $(this).attr('src', $(this).attr('data-tablet'));
    });
  }
});
like image 155
Christian Zosel Avatar answered Feb 08 '23 10:02

Christian Zosel