kodie
3/14/2017 - 2:42 PM

A small piece of Javascript/jQuery that will update the style of an element depending on the screen size.

A small piece of Javascript/jQuery that will update the style of an element depending on the screen size.

<div class="section container-fluid align-center data-style" data-style-0="background-image:url('<?=IMAGES?>/apples-mobile.png')" data-style-500="background-image:url('<?=IMAGES?>/apples.png')">
  <p>Insert Content Here</p>
</div>
(function($) {
  $(window).on('load resize', function() {
    $('.data-style').each(function() {
      var me = $(this);
      $.each(this.attributes, function() {
        if (this.name.substring(0, 11) == 'data-style-' && window.innerWidth >= this.name.substring(11)) {
          var styles = this.value.split(';');
          for (i = 0; i < styles.length; i++) {
            var style = styles[i].split(/:(.+)/);
            me.css(style[0], style[1]);
          }
        }
      });
    });
  });
})(jQuery);