beano
beano

Reputation: 952

Simple JQuery Lazyload example

I am trying to get a basic example of lazyload running, so an image only loads on click of a button.

https://jsfiddle.net/5rbhsmmc/3/

html

This text and 
<button class="frequently_asked">this button</button><br><br>
Image to be displayed only when the button is clicked.
<img class="lazyload" src="[image source]"/>

javascript

$('.frequently_asked').click(function() {
$('.lazyload').lazy({
bind: "event",
delay: 0
});
})

Any guidance is appreciated

Upvotes: 1

Views: 5531

Answers (1)

JasonB
JasonB

Reputation: 6378

You could set the src as a data attribute and then copy that over to the image source when the button is pressed.

$('.frequently_asked').click(function() {
    lazyLoadImages( $('.lazyload') );
});

var setImageSrcFromDataAttribute = function( imageElement ) {
    let imageUrl = imageElement.data( 'src' );
    imageElement.attr('src', imageUrl);
}

var lazyLoadImages = function( imageElements ) {
    imageElements.each( function() {
        setImageSrcFromDataAttribute( $( this ) );
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This text and
<button class="frequently_asked">this button</button><br><br> Images to be displayed only when the button is clicked.
<img class="lazyload" data-src="http://via.placeholder.com/350x150" />
<img class="lazyload" data-src="http://via.placeholder.com/400x200" />
<img class="lazyload" data-src="https://docs.google.com/drawings/d/e/2PACX-1vTb39GuFAvCPzFXXkPfdOMbS50Si5IN2OudxLQNyTxLzuOu5uVeDnEeZXTX9ie04nsXSYBQEjckQPMg/pub?w=986&h=691" style='width:100%;max-width: 700px;' />

Upvotes: 2

Related Questions