Forum Moderators: open
However, I have a small problem.
When my page opens I have couple of images and links that have "onmouseover" js events.
There are two to be exact:
stopscroll()
showpreview()
If a user moves his/her mouse over this portion quickly, before the functions load, error console will report an error.
This is normal, as the mentioned functions are still not available.
As these are the only two functions that cause "trouble" among many I load at the end, I was thinking.. could I add this to my HEAD:
function stopscroll(){
}
function showpreview(){
}
In such way the errors will not be produced, as functions are already available.
Naturally, this will also mean that I'll end up with duplicated functions.
Although the later will overwrite the first two that are empty, could this be a problem?
I'm reluctant to include the full functions of those two in the HEAD part as they are interconnected with many others that follow.
Hope I was somewhat clear : )
Thanks !
also, your second functions would not be deleared as there are already 2 functions with the name it will throw a "function already decleared error" i belive it will anyway..
i would just set the events for those link after the page has loaded, use prototypes Event functions or make your own
window.load = function(){
document.getElemntById('myele').onmouseover = stopscroll();
}
ect.. that would stop your errors because the functions would only be set once they've been called.
why not just move the calling of your custom libs into head? is where they belong anyway
The best approach is to attach your event handlers (or preferably, event listeners) when you know they will be available. I'm assuming you have inline event handlers... that is, in your HTML code you have something like:
onmouseover="stopscroll();showpreview();"
Keep your HTML markup as pure as possible. Separate out the behavior (JavaScript) layer from your content. This way, when you need to change behavior, you only need to make those changes in the JavaScript layer.
Kings on steeds was heading in the right direction. His example shows methods that set the event handlers rather than event listeners. The problem with that approach is that it can still be overwritten. For example, perhaps you load a 3rd party script that also defines window.load. If you load that after you set window.load then your code will be replaced with the 3rd party code.
With event listeners, you can attach as many listeners as you want to a particular event, and they won't step on each other. As mentioned, the Prototype library has methods to do that, as do jQuery and the Yahoo UI Library (among others). Personally, I prefer the Yahoo UI Library's Event Utility [developer.yahoo.com]. Here's what that code might look like:
YAHOO.util.Event.onDOMReady(function () {
YAHOO.util.Event.on('myel', 'mouseout', function () {
stopScroll();
showpreview();
});
});
Hope this helps.