Let's say we need to display 2 different images for mobile and desktop. We would usually do something like this:
HTML
<div class="container"></div>
CSS
.container {
background-image: url('image-for-mobile.jpg');
}
@media (min-width: 1024px) {
.container {
background-image: url('image-for-desktop.jpg');
}
}
But what happens when we are getting those images from the server? Let's say from Wordpress or any other source?
One way to do it, would be:
HTML
<div class="container for-mobile" style="background-image: url(<?php echo $img_for_mobile; ?>);"></div>
<div class="container for-desktop" style="background-image: url(<?php echo $img_for_desktop; ?>);"></div>
CSS
.for-mobile {
display: block;
}
.for-desktop {
display: none;
}
@media (min-width: 1024px) {
.for-mobile {
display: none;
}
.for-desktop {
display: block;
}
}
For obvious reasons, even though this "works" this is not right because we are repeating the markup. What if we have a ton of content inside '.container'? We would have to repeat all that, only to have a different background image.
Another option would probably be passing the variables as data attributes and then with jQuery getting those variables and assigning the right background image in relation to the screen size. Something like this:
HTML
<div class="container" data-mobile="<?php echo $img_for_mobile; ?>" data-desktop="<?php echo $img_for_desktop; ?>"></div>
jQuery
// This is pseudo code, not tested
var imgForMobile = $('.container').data('mobile');
var imgForDesktop = $('.container').data('desktop');
$(window).on('resize', function() {
if ($(window).width() < 1024) {
$('.container').css('background-image', 'url(' + imgForMobile + ')');
}
else {
$('.container').css('background-image', 'url(' + imgForDesktop + ')');
}
});
How could we attack this situation in a more elegant and proper way? Any thoughts would be much appreciated. Thanks in advance!