Search code examples
javascriptdomiframescrolllisteners

Javascript Avoid Overwriting Listener


I'm developing a piece of javascript which will run inside a non-friendly iframe. Fortunally I have an interface which permits me to run javascript inside the iframe parent page but this is not the problem.

The problem is: in my code I need to attach a function to the window.onscroll event of the iframe parent page. Unfortunately I don't know from the beginning on which websites my code will run so I don't know if they already have a function attached to window.onscroll

What will happen if I do a window.onscroll = function(){...} while the website already have one? Will it be overwritten? If yes: is there a way to avoid this?

I hope I've explained myself. Thank you in advance!


Solution

  • You can do:

    var oldHandler = null;
    
    if('function' == typeof window.onscroll) {
      oldHandler = window.onscroll; 
    }
    
    window.onscroll = function(ev) {
      // your stuff...
      if(oldHandler) oldHandler.call(window, ev);
    }