Skip to content

Instantly share code, notes, and snippets.

@ritcheyer
Created September 11, 2014 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ritcheyer/153ae5487c2ffd22564b to your computer and use it in GitHub Desktop.
Save ritcheyer/153ae5487c2ffd22564b to your computer and use it in GitHub Desktop.
ok so long story short, i can't use CSS and media queries to swap images as I need the sections to shrink/grow dynamically, so i created a function to switch out an image's source attribute based on page width (if less than 625px switch this, else use that). Works great save for one piece. there's a bit of a flicker when resizing the browser wh…
(function (window, document, $, Drupal) {
"use strict";
Drupal.behaviors.homepage_hero_height = {
attach: function (context) {
var allHomepageImages = $('.section-hero'),
thisHomepageImage;
window.onload = function() {
swapImages();
for (var i = 0; i <= allHomepageImages.length; i++) {
thisHomepageImage = allHomepageImages[i];
if($(thisHomepageImage).parent('.hero-container').hasClass('section-initial')) {
$(thisHomepageImage).parent('.hero-container').addClass('lazy-loaded');
}
if($(thisHomepageImage).hasClass('lazy-load')) {
$(thisHomepageImage).removeClass('lazy-load').parent('.hero-container').addClass('lazy-loaded');
}
}
};
$(window).resize(function() {
var timeout = setTimeout(swapImages(), 100);
clearTimeout(timeout);
});
/*
* Swap image if the following conditions have been met:
* 1. If window width on load is:
<= 640px, swap `'-original` for `-touch`
> 640px, swap `'-touch` for `-original`
* 2. If window width on resize is
<= 640px, swap `'-original` for `-touch`
> 640px, swap `'-touch` for `-original`
* 3. If src image is already `-touch` or `-original` do not swap
*/
function swapImages() {
$(allHomepageImages).each(function(index, value) {
if ($(window).width() < 625) {
if($(this).attr('src') !== $(this).data('touch-src')) {
$(this).attr('src', $(this).data('touch-src'));
}
} else {
if($(this).attr('src') !== $(this).data('src')) {
$(this).attr('src', $(this).data('src'));
}
}
});
}
}
};
}(this, this.document, this.jQuery, this.Drupal));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment