views:

2436

answers:

5

I have a method that is instantiated on page load. The method fires two events, window.onload and image.onclick. The problem is only one of the event works at any given time (ie: if i comment image.onclick method, window.onload method works). How do i get both to work?

This works fine in Firefox (mozilla) but not in IE

example

test.method = function()
{
    window.onload = this.doSomeWork;

    for (i = 0; i < images.length; i++) {
        var image = images[i];
        image.onclick = this.imageClickEvent;

    }
}
A: 

Look at the code on a page with Firefox 3. Then open the Firefox Error Console (Ctrl Shift J) to see which line is breaking. Then update your question with the new info.

tyndall
+1  A: 

The problem us that you can only have one onload event.

I recommend that yuu should try the addEvent method found here:

http://ejohn.org/projects/flexible-javascript-events/

tan
There is only one onload event. The other is the onclick event. Do you mean to say that there can be either onload or an onclick event?
DK
if test.method() is executed onload, there are two methods/functions added to onload, only the last will be added.
tan
+1  A: 

There's not really enough information in the question to figure out what's going wrong, but things to look at include:

  • is the code in the doSomeWork() or imageClickEvent() expecting to receive a ‘this’ that points to anything in particular? Because it won't, when you peel a method off its owner object to assign to an event handler.

  • is there another method writing to window.onload, or image.onclick, that you might be overriding?

bobince
A: 

Perhaps you should be adding an event listener here, and not trying to capture window.onload?

Kent Brewster
A: 

after you fire the test.method on page load, you overwrite your window.onload with a new value: this.dosomework, so within the time frame of the body load, you call the first function, then immidiately overwrite, then second function takes over, and carries out... did you try to push the window.onload statement way to the bottom of the test.method? my guess if the function block is too long, the second window.onload is never gonna be carried out, because the window has already finished loading, its milliseconds, but thats all it takes

apparently in firefox the function is carried out before it gets overwritten, or maybe appeneded to the current onload, not sure about technicalities. again, try to push onload to the bottom and see what happens

you should not really call an onload function within any other function that is called after body load, because no matter how careful you are you cannot depend on the fact that the loading time frame is long enough to contain both events, you should append to window.onload before the body tag is called (or finished) to make sure the event is caught.

Ayyash

related questions