Skip to content

Instantly share code, notes, and snippets.

@jonkpirateboy
Last active August 29, 2015 14:15
Show Gist options
  • Save jonkpirateboy/33f45cd7afa1227559c0 to your computer and use it in GitHub Desktop.
Save jonkpirateboy/33f45cd7afa1227559c0 to your computer and use it in GitHub Desktop.
Simple responsive images, jQuery
<?php
function fmd_child_setup() {
add_image_size( 'header', 1170, 400, true ); //(cropped)
add_image_size( 'mobileHeader', 750, 250, true ); //(cropped)
}
add_action( 'after_setup_theme', 'fmd_child_setup' );
?>
<?php
$image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'header');
$imageMobile = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'mobileHeader');
?>
<img class="responsive-img" alt=""
data-desktop-src="<?php $image[0]; ?>"
data-mobile-src="<?php $imageMobile[0]; ?>">
<div class="responsive-bg-img"
data-desktop-src="<?php $image[0]; ?>"
data-mobile-src="<?php $imageMobile[0]; ?>"></div>
<!-- use bootstrap to target mobiles in footer.php -->
<div class="visible-xs" id="detect-xs"></div>
$(document).ready(function() {
responsiveImages();
});
var timer;
$(window).resize(function () {
timer = setTimeout(function () {
responsiveImages();
}, 500);
});
function responsiveImages() {
$('.responsive-bg-img').each(function() {
if ($(this).attr('data-mobile-src')) {
mobileSrc = $(this).attr('data-mobile-src');
desktopSrc = $(this).attr('data-desktop-src');
if (isMobile()) {
$(this).css('background-image','url(\''+mobileSrc+'\')');
} else {
$(this).css('background-image','url(\''+desktopSrc+'\')');
}
}
});
$('.responsive-img').each(function() {
if ($(this).attr('data-mobile-src')) {
mobileSrc = $(this).attr('data-mobile-src');
desktopSrc = $(this).attr('data-desktop-src');
if (isMobile()) {
$(this).attr('src',mobileSrc);
} else {
$(this).attr('src',desktopSrc);
}
}
});
}
function isMobile() {
if($('#detect-xs').css('display') == 'block') {
return true;
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment