Skip to content Skip to sidebar Skip to footer

Javascript-How To Detect Scroll Event In Iframe?

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 u

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
    });
});

Solution 3:

I have faced the issue and here's one of my implementation.

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);
    }
  }
}

Post a Comment for "Javascript-How To Detect Scroll Event In Iframe?"