Last active
September 21, 2017 14:55
-
-
Save Chippd/b5738d5e6ededac0c5db4e5a9a74b17b to your computer and use it in GitHub Desktop.
find out how wide and high you need your background images need to be on a responsive layout
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
// for each div on page with a background image | |
// show a label in its top right corner with the max height and width values | |
// When page is resized, calculate | |
// create size display element | |
let sizeDisplayStyles = "style='position: absolute;top: 0;right: 0;padding: 10px;background: navajowhite;'"; | |
let displayEl = `<span class='sizeDisplay' ${sizeDisplayStyles} data-w="0" data-h="0" >waiting for page resize...</span>` | |
function magic () { | |
let els = document.querySelectorAll("*") | |
for (var i = 0, len = els.length; i < len; i++) { | |
el = els[i]; | |
if (el.currentStyle) { | |
if( el.currentStyle['backgroundImage'] !== 'none' ) { | |
// console.log("bg-found:", el) | |
jQuery(el).prepend(displayEl) | |
} | |
} | |
else if (window.getComputedStyle) { | |
if( document.defaultView.getComputedStyle(el, null).getPropertyValue('background-image') !== 'none' ) { | |
// console.log("bg-found:", el) | |
jQuery(el).prepend(displayEl) | |
} | |
} | |
} | |
} | |
magic() | |
// do stuff on window resize | |
window.addEventListener('resize', function(){ | |
console.log('page resized') | |
// loop over all .sizeDisplay elements | |
// get the width and height of its parent element | |
// save them to data attributes and update the text within span | |
// we want the max width and height (add logic to compare) | |
jQuery('.sizeDisplay').each(function(i){ | |
// console.log('loop:', jQuery(this)); | |
// Get parent el and width, height | |
let parent = jQuery(this).parent(); | |
console.log("parent", parent); | |
let pWidth = jQuery(parent).outerWidth(); | |
let pHeight = jQuery(parent).outerHeight(); | |
console.log("parent dimensions:", pWidth, pHeight) | |
// Get current width, height stored in data attributes | |
let curWidth = jQuery(this).attr('data-w'); | |
let curHeight = jQuery(this).attr('data-h'); | |
let toUpdate = false; | |
if(pWidth > curWidth){ | |
jQuery(this).attr('data-w', pWidth); | |
toUpdate = true; | |
} | |
if(pHeight > curHeight){ | |
jQuery(this).attr('data-h', pHeight) | |
toUpdate = true | |
} | |
if(toUpdate) updateText() | |
}) | |
}, true); | |
function updateText(){ | |
jQuery('.sizeDisplay').each(function(i){ | |
// get width and height from data attributes | |
// set text approppriately | |
jQuery(this).text("width: " + jQuery(this).attr('data-w') + ", height: " + jQuery(this).attr('data-h')) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment