robert
robert

Reputation: 21

change srcset attribute value in picture tag

<picture class="pic_test">
  <source media="(min-width:450px)" srcset="1190.jpg">
  <source media="(min-width:900px)" srcset="120.jpg">
  <img src="new.jpg" alt="Flowers" style="width:auto;">
</picture>

I want to check the source media attribute is 450px or not and based on the result, i have to change the srscet attribute.

Thanks in Advance

Upvotes: 0

Views: 3871

Answers (3)

mplungjan
mplungjan

Reputation: 178094

You mean

var $pic = $("picture"), $source=$pic.find("source"), media=$source.attr("media");
if (media.indexOf("450px")!=-1) $source.attr("srcset","small.jpg");

If you need specific source:

$("picture").find("source").each(function() {
  if ($(this).attr("media").indexOf("450px")!=-1) {
    $(this).attr("srcset","small.jpg");
  }
});

OR directly using the attr:

$('[media="(min-width:450px)"]').attr("srcset","small.jpg");

You may have to escape some of the - or :

Upvotes: 3

Alexander Solonik
Alexander Solonik

Reputation: 10230

You can simply use a jQuery attribute selector selector and change the srcset attribute like so:

$('[media^="(min-width:450px)"]').attr('srcset' , 'newSrcSet.jpg')

This would serve you better then something like $("source:eq(0)"), just incase the order of your source attribute changes.

Upvotes: 0

St&#233;phane Ammar
St&#233;phane Ammar

Reputation: 1454

You can use an javascript Image and get its width :

var image = new Image();
image.src = $("source#id??").attr("srcset");
image.onload = function() {
    var width = image.width;
    if(width == 450){
        //do stuff
    } else {
       //do other stuff
    }
}

Upvotes: 0

Related Questions