JavaScript: Load Images in a div after clicking a button

24,842

Solution 1

I would suggest using an attribute on the img tags to store the intended src attribute, then apply it on the button click. This would avoid having to maintain a list of src urls in your JavaScript.

HTML

<button onclick="show()">Show Images</button>
<hr>

<div id="id1" class="class1">
  <img data-src="http://lorempixel.com/400/200" alt="">
  <img data-src="http://lorempixel.com/400/200" alt="">
  <img data-src="http://lorempixel.com/400/200" alt="">
  <img data-src="http://lorempixel.com/400/200" alt="">
</div>

<hr>

JS

function show() {
  document.getElementById('id1').style.maxHeight = "200px";
  var images = document.querySelectorAll("#id1 img");
  for(var i = 0; i < images.length; i++)
  {
    images[i].src = images[i].getAttribute('data-src');
  }
}

Code pen - http://codepen.io/anon/pen/KrZvpJ

Solution 2

Here's the working fiddle https://jsfiddle.net/6ve7ub79/

You can do it easily using jQuery

jQuery

$(document).ready(function(){
$('button').bind('click', function(){
$('.i1').attr('src', 'img1.jpg');
$('.i2').attr('src', 'img2.jpg');
$('.i3').attr('src', 'img3.jpg');
$('.i4').attr('src', 'img4.jpg');
});
});

HTML

<button onclick="show()">Show Images</button>
<hr>
<div id="id1" class="class1">
<img class="i1" src="" alt="">
<img class="i2" src="" alt="">
<img class="i3" src="" alt="">
<img class="i4" src="" alt="">
</div>
<hr>

CSS

.class1 {
  transition:max-height 1s;
}
Share:
24,842
Tanasis
Author by

Tanasis

Updated on December 03, 2020

Comments

  • Tanasis
    Tanasis over 3 years

    I have a hidden div (by using max-height and transition) that show up when I click a button. This div contains several images that load up when you first load the site. I would like them to load when I click the button to show the div, to make the site lighter.

    <!DOCTYPE html>
    <html>
    <head>
      <style>
        .class1 {
          max-height:0px;
          transition:max-height 1s;
          overflow:hidden;
        }
      </style>
      <script>
        function show() {
          document.getElementById('id1').style.maxHeight = "200px";
        }
      </script>
    </head>
    <body>
      <button onclick="show()">Show Images</button>
      <hr>
    	
      <div id="id1" class="class1">
        <img src="img1.jpg" alt="">
        <img src="img2.jpg" alt="">
        <img src="img3.jpg" alt="">
        <img src="img4.jpg" alt="">
      </div>
    	
      <hr>
    </body>
    </html>