javascript - HTML Load Elements on Click? -
so have new website, blog , need reduce load time loading elements when user clicks button. post pictures (with captions) this:
<table> <tr> <td> <p>caption</p> </td> </tr> <tr> <td> <img src="path"> </td> </tr> </table> now want 10 pictures appear @ time , button @ bottom of page load 10 more. can't use show/hide or visibility becuase images still downloaded along page, not displayed. i've been web designing little on year don't know js , jquery.
its going fixed in future if want see in current state @ http://thedrawingblog.com in gallery/posts section.
one way use hidden attribute , data-* attribute.
<img id="img-to-show" hidden data-src="path/to/image.jpg" /> <button id="show-img-btn">show image</button> when want show images:
document.getelementbyid('show-img-btn').addeventlistener('click', function(){ var image = document.getelementbyid('img-to-show'); image.removeattribute('hidden'); image.src = image.dataset.src; }); i'm not sure structure you're using multiple images, makes enough sense can transform needs:
example html:
<div id="images"> <div hidden> <div>caption</div> <img data-src="path/to/image.jpg" /> </div> <div hidden> <div>caption 2</div> <img data-src="path/to/image2.jpg" /> </div> <div hidden> <div>caption 3</div> <img data-src="path/to/image3.jpg" /> </div> ... </div> <button id="show-img-btn">show image</button> js:
document.getelementbyid('show-img-btn').addeventlistener('click', function(){ // hidden divs var imagedivs = document.getelementbyid('images').queryselectorall('[hidden]'); // convert array, , slice out first 10. var imagedivsarray = [].slice.call(imagedivs,0,10); // loop through divs, showing each one, // , setting src of child <img> imagedivsarray.foreach(function(el,idx,arr) { // remove `hidden` attribute el.removeattribute('hidden'); // grab child image var img = el.getelementsbytagname('img')[0]; // set src img.src = img.dataset.src; }); }); https://jsfiddle.net/jsdn46lk/
there definite optimizations made here, unless you're loading large amount of images, should fine.
Comments
Post a Comment