Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
swap WordPress template partial by screen size / media query
(function ($, window, document, undefined) {
"use strict";
$(function() {
var swapContent = debounce(function() {
var currentSize = $(window).width();
var swapPath = '/wp-content/themes/twentyseventeen/template-parts/';
var swapSizeObj = { small: 1, medium: 639, large: 1023, xlarge: 1199 }
var swapSizes = Object.values(swapSizeObj);
var filteredSize = swapSizes.filter(function(smaller) {
return smaller < currentSize;
});
// thisSize gets largest 'smallerThan' size in array to match current screen size
// thisScreen gets associate template
var thisSize = filteredSize.pop();
var thisScreen = getKey(swapSizeObj,thisSize);
// ------------------------------------------------------
var dataSwaps = document.querySelectorAll('[data-swap]');
for (var i = 0; i < dataSwaps.length; i++) {
var thisID = '#' + dataSwaps[i].id;
var pageID = dataSwaps[i].dataset.pid;
var swapData = dataSwaps[i].dataset.swap;
var swapObj = JSON.parse(swapData);
var thisView = swapObj[thisScreen];
if ( thisView === undefined ) {
// grab last screen size in list then
var keys = Object.keys(swapObj);
var lastScreen = keys.slice(-1)[0];
thisView = swapObj[lastScreen];
}
var loadThis = swapPath + thisView + '?pid=' + pageID;
$( thisID ).load( loadThis );
}
// -----------------------------------------------------
}, 100);
swapContent();
// for finding key by val
// e6: const getKey = (obj,val) => Object.keys(obj).find(key => obj[key] === val);
var getKey = function getKey(obj, val) {
return Object.keys(obj).find(function (key) {
return obj[key] === val;
});
};
// debounce to keep function from firing until resize event over
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
window.addEventListener('resize', swapContent);
});
})(jQuery, window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment