Jump to content

Image onLoad


donspeck

Recommended Posts

I typed the code below into the Tryit Editor v1.4 to see whether the onLoad function would properly wait until an image was loaded before being called. It worked perfectly; turn off my modem and no message until I turned it back on and the image was loaded. Then I copy and pasted it into a file, loaded into FF2 and IE6, cleared their cache, turned off the modem, but the messages would appear immediately in both.

<html><head><script type="text/javascript">function load(){alert("Page is loaded");}</script></head><body><script type="text/javascript">var image1 = document.createElement('img');document.images[0] = image1;image1.src="http://i96.photobucket.com/albums/l162/donspeck/engulfed/Sunsets/1000.jpg" image1.onLoad = load();alert("Hi");</script></body></html>

I did expect the Hi to come up immediately since the onLoad should have just registered a function to be called on another event, but I think thats another topic.

Link to comment
Share on other sites

The code you have there looks correct I am not sure what is causing this behavior.When you say you loaded it into FF2 and IE6 what do you mean? YOu have the file on your PC and you just double clicked the file?Are you running this on a localhost server (IIS or apache)? Do you use a hosting company?I am just throwing htese out here, I am not sure what to tell you. If you are not already, upload the page to a live webserver, if you do not have access to one, awardspace.com has free accounts.

Link to comment
Share on other sites

Good tip on the code location. I was executing it from a local drive with the image file on the net. This allowed me to turn off my modem to test the code; the local html loads and runs and the image load waits. I was assuming the Tryit Editor was operating in the same fashion; it appeared as if the code was already in my browser and would execute without accessing the internet. However, the Tryit Editor was not running the html code until the modem was turned back on; which is why the Hi message did not appear immediately as it should.The code is incorrect. Parenthesis should be omitted from the function name when assigning a value to the onLoad variable (all function name variables?); i.e. image1.onLoad = load; this works. I guess this threw me off because all syntax errors I've encountered before were ignored by the browser and nothing happened; in this case the function was executed immediately.

Link to comment
Share on other sites

Correction: image1.onLoad = load will NOT work image1.onload = load worksThis error fails as I would expect; nothing happens.Javascript appears to be case sensitive, while html is not. The W3Schools HTML DOM reference incorrectly specifies the name with the capital L for the window object (there is no reference to the onload event under the Image object ?) but correctly uses the lowercase l in the Javascript tutorial and reference, however, oddly enough, when searching for onLoad on W3Schools there are two seemingly identical pages in the jsref directory, jsref_onLoad.asp and jsref_onload.asp.I know this seems nit picky but for a newbie it's very frustrating to spend hours tinkering with code trying to figure out why its not acting right to find out its l not L and not "l" in quotes or no (). Anyway, maybe I just need a better syntax checker. (Using PSPad now, trying to do it free til I know if I'm any good)Who came up with the lower case first letter then capital letters in the middle of labels anyway?

Link to comment
Share on other sites

Here is a list of the different events:http://devguru.com/technologies/javascript/10909.aspI think the Javascript reference on W3Schools is a little confusing, it's hard for me to find what I'm looking for. Also, all of the events on the W3Schools page are listed in lowercase, the events on that devguru page are all in camelcase, except for the onload. I think basically the rule is that if you use the event in javascript code, it is always in camelcase, like this:document.onLoad = ...But, if you use it in the attribute list for a tag, it should be lowercase. All attributes should be lowercase:<body onload = ...

Link to comment
Share on other sites

justsomeguy: I think devguru has it right, from what I've tested onload must be all lowercase in Javascript and can be any combination of upper or lower case in HtMl.jesh: I haven't tested all the events for case sensitivity but I did test setTimeout and it only worked in CamelCase. This is going to get really scary if some things in Javascript are case sensitive and some things are not.

Link to comment
Share on other sites

Validation is great, but I'm talking about when your up all night trying to get a page working for a client that has a show today. From what I've seen the major browsers accept HtmL in any case combination but Javascript is strictly case sensitive ( great, now I can write that OnMoUsEoVeR function I've been dreaming about )XML requires lowercase, my code was in lowercase except where I felt instructed to CamelCase, no problem.Speaking of purism, this is a Javascript (JavaScript?) forum.Hey, I'm getting really sarcastic, time for sleeeeeeeeeeeeeeeeeeeeeeep

Link to comment
Share on other sites

I've been trying to sum up this syntax issue and it seems like I'm not the only one confused about when to use CamelCase, even the authors of javascript couldn't maintain a standard (i.e. string object methods include toUpperCase and ToLowerCase but also fontcolor and fontsize).devguru incorrectly lists the names of events (except for onload) in CamelCase. W3Schools incorrectly lists event names in CamelCase on it's window object reference page but correctly in all lowercase on it's javascript event reference page. However, neither have any examples, that I could find, that reference the event labels in javascript, only in html. W3Schools uses valid xhtml, devguru does not.To summarize: xhtml - everything, except text displayed on the page, should be lowercase javascript - case sensitive, leans toward lowercase but CamelCase applied whimsically no rules for when an uppercase letter will appear in a label so each must be tested individually

Link to comment
Share on other sites

What I am saying is that choco's comment (and yours) is totally irrelevant to this topic which is javascript syntax.The code I submitted validates XHTML 1.0 Strict (Why do they capitalize XHTML when they want everything in the document to be lower case? I'm getting a headache!)Is there a way to validate or syntax check javascript?

Link to comment
Share on other sites

For the most part - with the exception of getElementById which probably ought to be getElementByID - javascript uses lowerCamelCase for all methods such as "indexOf", "setTimeout", "getUTCMonth", etc. For events, it uses lowercase. Every programming language I've come across has these little idiosyncrasies that you just have to get used to.

Link to comment
Share on other sites

I got used to the first idiosyncrasy I found in javascript by pulling my hair out for two days; I was hoping I could get used to any other ones by finding a list of LOOKOUT for this items or a synopsis of protocol like I submitted and jesh nicely wrapped up in one sentence (although what about fontcolor and fontsize for the string object)aspnetguy I'll take a look at that later; surfs up! gotta go skim.Thanks Guys

Link to comment
Share on other sites

I don't know about fontcolor and fontsize, I've never used them. You're better off using the HTML DOM if you want to affect the style of an element. Something like this:

var mydiv = document.getElementById("mydivid");mydiv.style.color = "#cc0000";mydiv.style.fontSize = "11px";

Or:

var mydiv = document.getElementById("mydivid");mydiv.className = "Red";  // this is the name of a css class

Link to comment
Share on other sites

aspnetguy: Thanks for the online software reference, I know how to search though. I was wondering if anyone knew of a program (hopefully free or online like W3C validation) that could find errors like the ones in the code I submitted. This may not be possible. I downloaded Northgate Coda which touts full js syntax parsing and it did not report any errors. (I hope that didn't sound like too much of an asshole, OK I am an asshole, but I wasn't trying to be mean.)jesh: You are totally missing my point, I don't care about what fontcolor and fontsize do but how they are spelled. You mentioned the html dom (shouldn't that reference be lowercase to conform with xml standard?); it too is plagued with dropouts from what could have been a lowerCamelCase standard, i.e. the anchor object properties charset and hreflang. I haven't looked for more but it doesn't matter, once you find one, the standard is broken.javascript is case sensitive, which is the only rule I know about for it's variable names, go ahead, make up AnyCraZfunc() name you want. What I've been trying to get at is if a convention or standard was set for the build in js objects and the dom variables. I was thrown off because a false standard of lowerCamelCase is implied because of it's prevalence and because HtmL's liberalness allows CamelCase versions of all lowercase js labels (like devguru using onKeyDown in it's examples).I have been trying to sum this up as simply as possible so other beginners won't fall into the same trap.For example, W3Schools has an alert in it's javascript variables section IMPORTANT! JavaScript is case-sensitive! I noticed that and made a mental note. I think it would be nice if it also said something like lowerCamelCase if used often in the html dom but is not a standard, each variable name must checked individually for use of capitalization.Anyway, in a simple example of CamelCase misspelling I would run the code, nothing happens, go back check the spelling or just try different spellings until the code did what I expected. However, the code I presented has an interesting combination of errors which made it much harder to determine what was going wrong. I thought it worked for at first! The image is loaded, the page is loaded message appears, then the Hi message appears. If anything was wrong the load function would not have executed and if anything was really wrong the script would have been stopped and no Hi message and an onerror event triggered right? nope! I didn't notice a problem until I went to more and bigger images (and started clearing my cache) and the onload function was obviously being called before the image was loaded.How do I fail thee, let me count the ways: image1.onLoad = load 1 error, onload misspelled, Hi msg displayed, load never executed. image1.onload = load() 1 error, parenthesis on func name, load executes immediately, no Hi msg. onerror function called, line not implemented image1.onload = Load 1 error, load misspelled, no Hi msg, load never executed. onerror function called, 'Load' not defined image1.onLoad = load() 2 errors, load executes immediately, Hi msg displays image1.onload = "load()" 1 error, quotes, Hi msg displayed, load never executed. image1.onload = load correct, Hi msg displayed, then load function executed after image loaded. however, if image is cached, load then Hi, just like 2 errors.Why are there no onerror calls except if parenthesis or function misspelled? Why is there an error 'line not implemented' but the function on that line is called?If javascript realizes Load is not defined and generates an error why not do the same for an undefined obect label?Why no error for an invalid argument in quotes?

Link to comment
Share on other sites

Why are there no onerror calls except if parenthesis or function misspelled?
When you spell the property or event name wrong, it is not technically an error. With Javascript objects, you can create your own properties at any time. So when you say image.onLoad, it's not an error because you are dynamically creating a new property called onLoad. The Javascript interpreter doesn't distinguish between that and thinking you are attempting to use an existing property, but misspelling it.
Why is there an error 'line not implemented' but the function on that line is called?
Assignment goes from right-to-left. So, in this statement:image1.onload = load();Since assignment goes from right-to-left, the first thing the interpreter does is execute the load function, and then it will assign the return value of the load function to the argument on the left side of the assignment operator (=). That is why the function gets executed. The error occurs because the return value of the load function (if any) is not the type of argument that onload is expecting, since it expects an object of type 'function'. 'Line not implemented' might indicate that the load function does not have any return value at all, and so you are assigning the onload event a value of null or undefined or something. It would probably be clearer to say something like 'invalid type for onload, function expected', but programming error messages are notoriously cryptic.
If javascript realizes Load is not defined and generates an error why not do the same for an undefined object label?
That's just not an error condition, instead of giving an error condition for something that is undefined, that thing just gets defined. It's very useful for creating your own objects, but granted it's not the easiest way to debug.
Why no error for an invalid argument in quotes?
I'm not sure about that one, but for whatever reason a string is an acceptable value for onload. It won't do anything, but it doesn't complain about it apparently.
Link to comment
Share on other sites

You are totally missing my point, I don't care about what fontcolor and fontsize do but how they are spelled. You mentioned the html dom (shouldn't that reference be lowercase to conform with xml standard?); it too is plagued with dropouts from what could have been a lowerCamelCase standard, i.e. the anchor object properties charset and hreflang. I haven't looked for more but it doesn't matter, once you find one, the standard is broken.
I don't think I'm missing your point. What I am missing is an understanding of why this is such a big deal for you. I understand that it adds an additional challenge when learning a new technology, but that's just part of learning it. Javascript is the way it is and we all have to accept that. If someone wants to write his/her own scripting language that conforms with a standard then s/he can have at it. Like I said earlier, these idiosyncracies are everywhere - the HTTP standard even has one with "referer" (should be referrer).
Link to comment
Share on other sites

justsomeguy: Great answers! It all seems so clear now. Only 996 questions to go (for man of 1000 questions).jesh: like I said in my last post I just wanted to raise a red flag for newbies and that it was the CamelCase error combined with an assignment error that really caused me problems.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...