jQuery: handling privacy agreements with the scroll event

jQuery: handling privacy agreements with the scroll event

How to make sure with jQuery that a user has actually read the contents of a privacy agreement.

A privacy agreement is a common feature that allows website owners to explain to their visitors all the legal conditions related to sensitive data. Usually this feature is implemented by creating a fixed-height block with a vertical scrollbar and a single checkbox to express a choice. The client-side problem here is to make sure that a visitor has actually read the legal statements before selecting the checkbox. This can be accomplished with jQuery and the scroll event.

We start with the following markup structure:


<div id="privacy-terms">
	<div id="privacy-wrapper"><!-- content here --></div>
</div>
<p id="agree">
	<label for="i-agree">
		<input type="radio" value="yes" id="i-agree" name="i-agree" /> 
		I agree
	</label>
</p>

The CSS code simply sets a stated height on the block and hides the corresponding checkbox:


#privacy-terms {
	width: 400px;
	height: 150px;
	overflow: auto;
	background: #eee;
}

#privacy-terms p {
    padding: 0 1em;
    line-height: 1.3;
}

#agree { display: none; }

The jQuery code is also simple. First, we save the heights of the outermost container and the innermost container along with the top offset of the outermost container into three variables.

Then we bind a scroll event to the outer container. Within the event's callback function we simply check whether the difference between the height of the outer wrapper minus the current top offset of the inner container (plus the top offset of the outer wrapper) is greater than the overall height of the inner wrapper.

If so, we show the checkbox:


$(function() {
	var $privacy = $('#privacy-terms'),
	    $privacyWrapper = $('#privacy-wrapper'),
		  $agree = $('#agree'),
		  height = $privacy.height(), // height of the outer wrapper
		  top = $privacy.offset().top, // top offset of the outer wrapper
		  privacyWrapperHeight = $privacyWrapper.outerHeight(); // height of the inner wrapper
	
	$privacy.on('scroll', function() {
			 if (Math.ceil(height - $privacyWrapper.offset().top + top) >= privacyWrapperHeight ) {
			 		$agree.show();
			 }
	
	});

});

[view-example url="http://codepen.io/gabrieleromanato/pen/Gmkef"]