super-user super-user - 2 months ago 16
CSS Question

jQuery + Bootstrap Grid - Show Images based on screen size

I have a web project and I use bootstrap's grid system. In my current set up, I display 3 images using

col-xs-4
so that 3 images are displayed on any screen size per row. However I want it now to display only 1 image when the screen size gets smaller. This is my original code:

<div class="row">
<div class="col-xs-4">
<img src="https://images.google.com/images/branding/googleg/1x/googleg_standard_color_128dp.png">
</div>
<div class="col-xs-4">
<img src="https://images.google.com/images/branding/googleg/1x/googleg_standard_color_128dp.png">
</div>
<div class="col-xs-4">
<img src="https://images.google.com/images/branding/googleg/1x/googleg_standard_color_128dp.png">
</div>
</div>


Desired output:

Desktop View:
enter image description here


Mobile View:

enter image description here

I am aware that I can simply set the
display to none
when the screen size goes below a certain break point but I want the web application to load only 1 image to make it faster (just using
display:none;
will still load the other 2 images)

Any suggestion how to do this?

My idea is to use jquery / javascript to generate html pages.
Here is the jsfiddle to play around: https://jsfiddle.net/Lb92rv84/1/

Answer

I used the html elements from the question.

$(document).ready(function(){
  var width = $(window).width();
  var newdiv1 = $('<div class="col-xs-4"></div>');
  var image = '<img src="https://images.google.com/images/branding/googleg/1x/googleg_standard_color_128dp.png">';
  var el = newdiv1.append(image);
  
  if (width >= 768){
  	//html for screen wider than 768
  	el.appendTo('.target').clone().appendTo('.target').clone().appendTo('.target');
  }else{
  	//html for screen smaller than 768
  	el.appendTo('.target');
  }
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="row">
    <div class="target"></div>
  </div>
</div>