- function $$(element)
- {
- return document.querySelector(element);
- }
- function closest(num, arr) {
- var curr = arr[0];
- var diff = Math.abs (num - curr);
- for (var val = 0; val < arr.length; val++) {
- var newdiff = Math.abs (num - arr[val]);
- if (newdiff < diff) {
- diff = newdiff;
- curr = arr[val];
- }
- }
- return curr;
- }
- function set_background(elem) {
- /*
- The function runs through every data-img attr and selects the one which
- is at least as wide / big as the viewport width - the url from this will
- replace the default background-image of the target element
- */
- let viewport = document.documentElement.clientWidth;
- var w, approx = (elem.dataset.width) / 100, sources = {}, widths = [];
- if (approx) {
- w = viewport * approx;
- } else {
- w = viewport;
- }
- console.log('viewport: ' + viewport);
- console.log('approx: ' + approx);
- console.log('w: ' + w);
- for (var i = 0; i < elem.attributes.length; i++) {
- let attr = elem.attributes[i];
- if (/^data-img-/.test(attr.nodeName)) {
- let width = attr.nodeName.replace(/^data-img-/, ''),
- url = attr.nodeValue;
- sources[width] = {
- 'width' : width,
- 'url' : url
- };
- widths.push(width);
- }
- }
- elem.style.background = 'url(' + sources[closest (w, widths)].url + ') no-repeat center center/cover';
- }
- var dynamic_images = document.querySelectorAll('.dynamic--image-bg');
- dynamic_images.forEach(function(element) {
- set_background( element );
- });
Recent Pastes