JAVASCRIPT 31
Dynamic--image-bg - set background By timo on 18th July 2018 04:31:43 PM
  1. function $$(element)
  2.   {
  3.     return document.querySelector(element);
  4.   }
  5.  
  6.   function closest(num, arr) {
  7.     var curr = arr[0];
  8.     var diff = Math.abs (num - curr);
  9.     for (var val = 0; val < arr.length; val++) {
  10.       var newdiff = Math.abs (num - arr[val]);
  11.       if (newdiff < diff) {
  12.         diff = newdiff;
  13.         curr = arr[val];
  14.       }
  15.     }
  16.     return curr;
  17.   }
  18.  
  19.   function set_background(elem) {
  20.     /*
  21.       The function runs through every data-img attr and selects the one which
  22.       is at least as wide / big as the viewport width - the url from this will
  23.       replace the default background-image of the target element
  24.      */
  25.     let viewport = document.documentElement.clientWidth;
  26.     var w, approx = (elem.dataset.width) / 100, sources = {}, widths = [];
  27.     if (approx) {
  28.       w = viewport * approx;
  29.     } else {
  30.       w = viewport;
  31.     }
  32.     console.log('viewport: ' + viewport);
  33.     console.log('approx: ' + approx);
  34.     console.log('w: ' + w);
  35.     for (var i = 0; i < elem.attributes.length; i++) {
  36.       let attr = elem.attributes[i];
  37.       if (/^data-img-/.test(attr.nodeName)) {
  38.         let width = attr.nodeName.replace(/^data-img-/, ''),
  39.             url   = attr.nodeValue;
  40.         sources[width] = {
  41.           'width' : width,
  42.           'url' : url
  43.         };
  44.         widths.push(width);
  45.  
  46.       }
  47.     }
  48.  
  49.     elem.style.background = 'url(' + sources[closest (w, widths)].url + ') no-repeat center center/cover';
  50.  
  51.   }
  52.  
  53.   var dynamic_images = document.querySelectorAll('.dynamic--image-bg');
  54.  
  55.   dynamic_images.forEach(function(element) {
  56.     set_background( element );
  57.   });

Paste is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.