Created
September 1, 2017 18:41
-
-
Save davideleuterius/fd8517d0b4df466f54aace7396f9e143 to your computer and use it in GitHub Desktop.
swap WordPress template partial by screen size / media query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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