Joe Joe - 2 months ago 16
HTML Question

load iframe on scroll down

i have a page with an iframe...
currently i used this code to load iframe on click..

here is my code

$('.a').click(function(){
var iframe = $("#b");
iframe.attr("src", iframe.data("src"));
});

<button class='a'>Load</button>
<iframe id='b' src='' data-src='index.php'></iframe>


but i also i want to load iframe on scroll down (500px from top)

can someone please help me how i can do this...

Thanks

Answer

Try this:

$(window).scroll(function() {
    var height = $(window).scrollTop();
    if(height  > 500) {
        var iframe = $("#b");
        iframe.attr("src", iframe.data("src"));
    }
});

If you want to only load one time after scroll with more than 500 you can add flag and equal it to false on page load then make it true inside scrolling event and check for this flag before you load iframe Example:

var isLoaded = flase;
$(window).scroll(function() {
    var height = $(window).scrollTop();
    if(height  > 500) {
        if(!isLoaded){
            var iframe = $("#b");
            iframe.attr("src", iframe.data("src"));
            isLoaded = true;
        }
    }
});