DK.
DK.

Reputation: 91

onload, onclick events

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 (i.e.: 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;

    }
}

Upvotes: 2

Views: 7714

Answers (5)

Ayyash
Ayyash

Reputation: 4409

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.

Upvotes: 1

Kent Brewster
Kent Brewster

Reputation: 2520

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

Upvotes: 0

bobince
bobince

Reputation: 536755

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?

Upvotes: 1

tan
tan

Reputation: 6105

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/

Upvotes: 1

BuddyJoe
BuddyJoe

Reputation: 71171

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.

Upvotes: 0

Related Questions