I’m not sure if I need the each() function here or if I can somehow do this with this. I’m trying to switch the src attribute based on the if statement. It works except that it switches them both to hifi1.jpg. How do I make it so it applies each img‘s data-websrc value to itself?
HTML:
<img class="airsrc" src="lofi1.jpg" data-websrc="hifi1.jpg" alt="example1">
<img class="airsrc" src="lofi2.jpg" data-websrc="hifi2.jpg" alt="example2">
JS:
jQuery(document).ready(function($) {
var airsrc = $('.airsrc');
airsrc.each(function() {
if ( Modernizr.mq('(min-width:480px)') ) {
var src = $(this).data('websrc');
airsrc.attr('src', src);
}
});
});
Update: Solution:
jQuery(document).ready(function($) {
if ( Modernizr.mq('(min-width:480px)') ) {
$('.airsrc').each(function() {
var $this = $(this);
var src = $this.data('websrc');
if ( src != '' ) {
$this.attr('src', src);
}
});
}
});
That works in browsers that support custom data attributes, which from my testing I’ve found to mean FF/Chrome/Opera/Safari. Maybe IE9. I think getAttribute can be used though for (older) IE.
It was applying to both, because you were applying it to the whole jQuery object
airsrc.You had to specifically reference the current element with
$(this)or…
Do it like the above code, which assigns
$(this)to$thisin order to cache it, for avoiding further lookups. Then you get its data and change its attribute.