In JavaScript there may be times you want to combine code onto an existing window event. In this case we will use window.onscroll.
In this example we already have assigned window.onscroll as the following:
window.onscroll = function() {
setTimeout("document.getElementById('myDiv').style.color='red';",200);
setTimeout("document.getElementById('myDiv').style.color='green';",400);
};
This causes the text color to blink within our div as we scroll. Of course this is only for example and serves no practical use… normally at least. Anyway, now we want to combine this with some other code.
So we now want to impose the new onscroll code:
function() { moveDiv() }
moveDiv in this case moves the div so it is always on screen while you move. (fyi, this is how I personally get around IE5’s lack of support for position:fixed)
So how do we impose our old code onto the new code? Well it’s kind of strange, but we have to be a bit sneaky about it and take advantage of JavaScript’s JSON logic. To do this, we simply add the old code within the declaration of the new code, such as:
var ScrollCode = eval(window.onscroll);
window.onscroll = function() { moveDiv(ScrollCode()) };
Yes I am using eval, and yes most people hate using eval, but if used correct it is actually very useful! So there is no harm in this case since the eval code does not involve any sort of user input.
So what happens in this code is simple. We call the new function moveDiv which references the variable ScrollCode which calls the function for the current onscroll code. As a result both codes are ran at the same time. This makes adding new code easy, and you can continue to add code in this same manor. It just continues to impose the code onto each other.
Anyway hope this helps, and please let me know if you have any issues with it. Good luck.
PS: Note that this method is meant to be used with window events. click events do not always require function usage. (i.e. window.onscroll = function() {};) Most window events do require this on modern browsers.