javascript-How to detect scroll event in iframe?
Solution 1
An iframe
does not have a scroll method, the document
of the iframe
does - you need to reference the inner document
rather than your <iframe>
tag.
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 more information
Solution 2
JavaScript provide us onscroll as an attribute which passes parameters (Can be a function). But we got iframe here, try the following code snippet (jQuery).
$("#yourFrameId").load(function () {
var iframe = $("#yourFrameId").contents();
$(iframe).scroll(function () {
//your code here
});
});
DevScripts
Updated on July 07, 2022Comments
-
DevScripts almost 2 years
I have a problem when I try add event scroll with iframe tage. generally, I use scroll event with div tag It was working well. but when I add scroll event in iframe tag to detect user scroll pdf page, It was not working. why cannot I access html elements in iframe?, I have code inspect below:
and I try to add javascript scroll event with iframe :
HTML Code:
<iframe id="myframe" src="doc.pdf"></iframe>
JavaScript Code:
document.getElementById('myframe').onscroll = function(){ alert('scrolling page'); };