nguyenvanduocit
1/10/2018 - 9:09 AM

responsive-background.js

function responsiveBackground () {
  var minDesktopBreakpoint = 992;
  var elements = document.querySelectorAll('.responsive-background');

  if (elements) {
    var mobileMediaQueryList = window.matchMedia('(min-width: ' + minDesktopBreakpoint + 'px)');
    mobileMediaQueryList.addListener(handleMediaQueryMatch);
    handleMediaQueryMatch(mobileMediaQueryList);
  }

  function setBackground (device) {
    elements.forEach(function (targetElement) {
      var dataKey = device + 'Background';
      if (targetElement.dataset.hasOwnProperty(dataKey)) {
        var backgroundImage = targetElement.dataset[dataKey];
        targetElement.style.backgroundImage = 'url("' + backgroundImage + '")';
      }
    })
  }

  function handleMediaQueryMatch (mql) {
    if (mql.matches) {
      setBackground('desktop');
    } else {
      setBackground('mobile');
    }
  }
}
window.onload = responsiveBackground;