I recently had a project where I had to require that a user scroll down the terms and conditions and privacy policy before they could check that they agree to them. I read everywhere that in order to get the position of how far down the scroll bar is you have to use $(element).scrollTop(). But this kept returning 0 no matter where the scroll handle currently was!
The solution is to use $(element).contents().scrollTop()
var position = $('#myIframe').contents().scrollTop();
That position is actually the number of pixels that are hidden above the top edge in the iframe. To figure out if the scroll bar is all the way at the bottom, you have to use a calculation including the height of the iframe and the height of the iframe contents.
If this equals true, then they have scrolled to the bottom:
$('#myIframe').contents().height()-$('#myIframe'). contents().scrollTop()-$('# myIframe').height()==0
Considering I wanted to warn them when they haven’t seen all the contents, this became my final piece of code to prevent them from checking a checkbox until they had scrolled all the way down:
//must scroll to bottom of terms to agree $('#checkAgree').click( function() { if($('#terms_iframe').contents().height()-$('#terms_iframe').contents().scrollTop()-$('#terms_iframe').height()>0) { alert("Please scroll through the terms and conditions before clicking agree"); return false; } });
I’m aware that there are ways to get this without jQuery, feel free to leave it in the comments. Hope that helps!
I should add that the iframe contents needs to be from the same domain, otherwise permission will be denied
Same domain means?
Excelent!! It worked perfectly, thanks for sharing (Y)
Can you show me full code ? Please….
//must scroll to bottom of terms to agree
$('#checkAgree').click( function() {
if($('#terms_iframe').contents().height()-$('#terms_iframe').contents().scrollTop()-$('#terms_iframe').height()>0)
{
alert("Please scroll through the terms and conditions before clicking agree");
return false;
}
});
Don’t you have to reference the parent element? The iframe is in the parent html…How do you reference it. I can’t get it to work the way you have it.
Yes, this needs to be ran from the parent page, which also needs to be on the same domain.
No work if I put PDF into iframe.