Javascript How to detect scroll event in iframe?

I have a problem when I try to add an event scroll with iframe tage. I usually use a scroll event with a div tag. He worked well. but when I add a scroll event to the iframe tag to define the user's scroll page, this does not work. why can't I access the html elements in the iframe ?, I have the code check below:

enter image description here

and I'm trying to add a javascript scroll event with iframe:

HTML code:

<iframe id="myframe" src="doc.pdf"></iframe> 

JavaScript Code:

 document.getElementById('myframe').onscroll = function(){ alert('scrolling page'); }; 
+2
javascript jquery html css iframe
source share
3 answers

JavaScript provides us with onscroll as an attribute that passes parameters (may be a function). But we got an iframe here, try the following code snippet (jQuery).

 $("#yourFrameId").load(function () { var iframe = $("#yourFrameId").contents(); $(iframe).scroll(function () { //your code here }); }); 
+9
source share

There is no scroll method in the iframe , document for the iframe - you need to reference the internal document , not the <iframe> .

You can reference it with iframe.contentDocument :

 var iframe = document.getElementById('frame'); iframe.contentDocument.body.innerHTML = 'a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>a<br>'; iframe.contentDocument.addEventListener('scroll', function(event) { console.log(event); }, false); 
 <iframe id="frame"></iframe> 

See https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement for details

+6
source share

I ran into a problem and here is one of my implementations.

 var currAgreementTab = this.get('parentController').get('currAgreement'); var contractContainer = Ember.$('div#marginContractContainer'); var iframe = contractContainer.children(currAgreementTab.element)[0].contentWindow; if (iframe) { iframe.onscroll = function() { var scrolledHeight = Ember.$(iframe).height() === Ember.$(iframe.document).innerHeight() ? Ember.$(iframe).height() : Ember.$(iframe.document).innerHeight() - Ember.$(iframe).height(); if (Ember.$(iframe).scrollTop() === scrolledHeight) { var currAgreementTab = that.get('parentController').get('currAgreement'); Ember.set(currAgreementTab, 'checkDisabled', false); } } } 
0
source share

All Articles