Detecting if scroll reached the bottom is never too easy. Because it mostly depends on how to style it. But while in an iframe the story id different. Below is how i did in any iframe.
Requirement
I had to create a end user license agreement screen where the agreement is served from backend and in frontend i will show the HTML. Obviously iframe was natural option because website styles will not interfere with the agreement styles.
I had to enable the agree button only when the user had scrolled down to the end of the iframe
Solution
This is how i did it. Below is the html part of the code.
<iframe id="user-license" #iframe style="overflow:hidden;height:90%;width:100%"
height="90%" width="100%" frameborder="0" wmode="transparent"></iframe>
In anguale component ts i added the content like below,
@Component({
selector: 'app-end-user-license',
templateUrl: './end-user-license-popup.component.html',
styleUrls: ['./modal-components.component.css', './end-user-license-popup.css']
})
export class EndUserLicensePopupComponent implements OnInit {
// Get the iframe element reference
@ViewChild('iframe', {static: false}) iframe: ElementRef;
userLicense = '';
isLoading: boolean;
enableAccept: boolean;
constructor(
private http: HttpService) {
}
ngOnInit() {
this.isLoading = true;
/* Get the end user license */
this.http.get('/terms-and-conditions/')
.then((res: any) => {
this.isLoading = false;
// Get the iframe's document reference
const doc = this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentWindow;
// Open the doc and add html in it
doc.open();
doc.write(res.html);
doc.close();
const self = this;
// Add scroll event
doc.addEventListener('scroll', function(event) {
console.log('event: ', event);
const iframe = self.iframe.nativeElement;
if (Math.ceil($(iframe.contentWindow).scrollTop()) === $(iframe.contentWindow).height() - $(iframe.contentWindow)[0].innerHeight) {
// Set true
self.enableAccept = true;
}
}, false);
})
.catch(err => {
console.log(err);
this.isLoading = false;
});
}
}
As you can see below is the important one line that detects if scrolled till the end. You can use either contentWindow or contentDocument. This will give access to the document inside the iframe.
if ($(iframe.contentWindow).scrollTop() === $(iframe.contentWindow).height() - $(iframe.contentWindow)[0].innerHeight)
Scroll events are always a huge problem. This was a simple solution that i came up with. Always print the event in console to check its keys and get the required data. Hope it helps and Let me know you thoughts in the comments.
Top comments (1)
I' not able to get any event onScroll in react