I have a registration form which contains a read-only textarea. I want to require any visitor to scroll to the bottom of the textarea, which contains terms and conditions or
Something like this should work:
$('#terms').scroll(function () {
if ($(this).scrollTop() == $(this)[0].scrollHeight - $(this).height()) {
$('#register').removeAttr('disabled');
}
});
Simply give terms an id, and set the register button to disabled in the html. I also made a little fiddle to show it working: http://jsfiddle.net/ETLZ8/
I recommend this rather, it handles zooming better.
$('#terms').scroll(function () {
if ($(this).scrollTop() + $(this).innerHeight() +2 >= $(this)[0].scrollHeight) {
$('#register').removeAttr('disabled');
}
});
The +2 handles a few scaling scenarios when scrolltop+innerheight is marginally below scrollHeight (for some reason I am too lazy to work out).
Other answers work perfectly, but I've put together a sample using a slightly different approach, one that doesn't tie the ability to submit to the button being disabled, so that it can be mixed with other validators and such.
$(function(){
var terms_were_scrolled = false;
$('#terms').scroll(function () {
if ($(this).scrollTop() == $(this)[0].scrollHeight - $(this).height()) {
terms_were_scrolled = true;
}
});
$('#terms_agreed').click(function( event ){
if( !terms_were_scrolled ){
alert('you must read all the way to the bottom before agreeing');
event.preventDefault();
}
});
});
HTML:
<form action="#">
<textarea id="terms" cols="100" rows="10">
Lorem Ipsum ....
</textarea>
<br />
<input type="checkbox" id="terms_agreed"/> I agree
<br />
<input type="submit">
</form>
Christian Varga's solution is absolutely correct, and can also be applied to a div. However, if you are using a div instead of a textarea, the div MUST NOT have any padding on it or it breaks.
My workaround for this was to place a div inside my styled div (with padding, rounded corners, and a border) to detect scrolling. So:
<div class="styled-div">
<div id="terms">
Lorem ipsum...terms text...
</div>
</div>
<input type="submit" id="register" value="Register"/>
The only possible drawback to this approach is if you add padding to the containing div, the scrollbar appears on the inner div, which may not look good to some users.
Use something like this inside the textarea:
onscroll="if(this.scrollTop+this.offsetHeight>=this.scrollHeight){/*enable the button*/}"
But what if JS is disabled?
I would prefer a scrollable div with the submit-button at the bottom. The user can't click the button without scrolling at the end, no matter if JS is on or off.