I have a srcset on my page
<img src="bg__x-large.png" srcset="bg__small.png 900w, bg__med.png 1200w, bg__large.png 1920w">
This is used by a parallax script, which right now just reads the src attribute
$(this).css('background-image', 'url(' + $(this).attr('src') + ')' );
to set this as the background image.
How can I read the correct src from the srcset with jquery?
I have a srcset on my page
<img src="bg__x-large.png" srcset="bg__small.png 900w, bg__med.png 1200w, bg__large.png 1920w">
This is used by a parallax script, which right now just reads the src attribute
$(this).css('background-image', 'url(' + $(this).attr('src') + ')' );
to set this as the background image.
How can I read the correct src from the srcset with jquery?
Share Improve this question asked Jun 21, 2016 at 8:50 tommuellertommueller 2,4963 gold badges33 silver badges49 bronze badges 1-
@newnoise there are multiple images in
srcset
which one you want to get; ? – Mairaj Ahmad Commented Jun 21, 2016 at 8:59
1 Answer
Reset to default 6Use the .currentSrc
property (as opposed to .src
) of the image to determine the active "src":
jq:
$(this).prop('currentSrc')
vanilla:
this.currentSrc
see mdc's HTMLMediaElement.currentSrc docs for more info.