Forum Moderators: open
<img src="image1.jpg" onmouseover="this.src='image2.jpg';" onmouseout="this.src='image1.jpg';" />
There are better ways of doing this, as well as 'more correct' ways, especially if the image is to be used as a link.
Fwiw, it's not ideal to have the js instructions appearing inline, but I guess 'the separation of content, style and script' is still only a dot on the horizon for some folk. ;)
You're supposed to use them (for the js to be correct) and without them, some browsers won't understand what you're asking and won't perform the swap, but may rightly throw a js error instead.
Absolutely. Well spotted.
I'd go as far as to say all browsers would throw an error. They'd assume that you're trying to reference a property (jpg) of an object that doesn't exist (image1).
Fwiw, it's not ideal to have the js instructions appearing inline, but I guess 'the separation of content, style and script' is still only a dot on the horizon for some folk. ;)
This is true too, and it's something I worry about. It's a possible drawback of forums altogether for code snippets like this.
If we were going for full separation of behaviour from content (and without touching on behaviors/XBL, whatever), then we'd have to quote the whole algorithm for searching the document and adding event handlers to appropriate elements. Once that's done, we'd have to go through the issue of onload event conflicts, and what to do if you want your elements 'enhanced' before the page has fully loaded - if you have a lot of images perhaps.
All that would be confusing and very repetitive. I don't see a clear answer myself.
'Enhancements' that need to be done before the page has finished loading are something I'd generally do on-the-fly using PHP - though that largely depends on exactly what was needed.
In most cases, I'd personally be content to use a function (stored externally) which is cited only minimally inline.
Whilst, we/I could go the whole hog and handle many things entirely remotely (thanks to the dom), that would have truly lost the original poster.
The connection between a function and its use during a js event is something that, imho, could be made clear in even a basic demonstration, whilst still offering the flexibility for the function to be reused for other elements throughout the site.
So, yeah, separation is commendable and always worth attempting to some degree, but I like to scale it according to the level of the person learning.
Even a single step in the right direction is one worth taking. :)