Javascript Best Practices Document v1.0

M

Matt Kruse

http://www.JavascriptToolbox.com/bestpractices/

I started writing this up as a guide for some people who were looking for
general tips on how to do things the 'right way' with Javascript. Their code
was littered with document.all and eval, for example, and I wanted to create
a practical list of best practices that they could easily put to use.

The above URL is version 1.0 (draft) that resulted. IMO, it is not a
replacement for the FAQ, but a more practical guide for fixing some of the
problems that commonly get pushed into web sites.

Any comments?

PS: Ignore the formatting. It's ugly, for now ;)

PPS: I know that there are exceptions to many of the 'best practices' in
very specific situations when approached by an experienced author, but the
goal of this document is to help the average joe developer fix common
problems and write more acceptable code.
 
G

Gérard Talbot

Matt Kruse a écrit :
http://www.JavascriptToolbox.com/bestpractices/

I started writing this up as a guide for some people who were looking for
general tips on how to do things the 'right way' with Javascript.

Good idea! I support such initiative.

Their code
was littered with document.all and eval,

You're most likely right. The top nr 1 problem with DHTML/javascript
code on the web is still the recourse to document.all. Still today, in
this very newsgroup, a lot of people are still promoting it in the name
of supporting MSIE 4 ... which I think is just stupid. Less than 0.5% of
internet/web users worldwide are still using MSIE 4 and the chances that
some DHTML/javascript stuff can effectively work on MSIE 4 is very slim.
So, I'd recommend to ditch document.all everywhere... including in this
newsgroup.

for example, and I wanted to create
a practical list of best practices that they could easily put to use.

The above URL is version 1.0 (draft) that resulted. IMO, it is not a
replacement for the FAQ, but a more practical guide for fixing some of the
problems that commonly get pushed into web sites.

Any comments?

PS: Ignore the formatting. It's ugly, for now ;)

The formatting is ok for me.


1- I think you should start with something as basic as explaining that
document.all is bad, wrong, deprecated, obsolete, etc..

2- The web standards way to reference a form input element is:

document.forms.namedItem("formname").elements.namedItem("inputname")

http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-1689064

http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-21069976

http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-76728479

3- "All forms should have a name attribute. Referencing forms using
indexes, such as document.forms[0] is bad practice."
name attribute for form was dropped in XHTML specification. So you may
want to add such nuance/relativity in there.

4- <form name="myform">
<input type="text" name="val1" value="1">
<input type="text" name="val2" value="2">
</form>
will trigger a validation markup error with a DTD strict.

5- "To fix this problem, Javascript needs a hint to tell it to treat the
values as numbers, rather than strings. Subtracting 0 from the value
will force javascript to consider the value as a number, and then using
the + operator on a number will perform addition, rather than
concatenation."
I think you may be in fact teaching a wrong trick. What's wrong with
offering to use parseInt(strValParam, indexParam) to achieve exactly
what you want to achieve... which is converting a string into an integer
or to use parseFloat(strValParam).

6- "This is why 'return false;' is often included at the end of the code
within an onClick handler."
I would remove that sentence. The sentence does not perfectly make
sense. Also, we have no idea what the doSomething() function does exactly...

7- "Often, links will just contain href="#" for the sake of simplicity,
when you know for sure that your users will have javascript enabled."
This is what a lot of people denounce also as bad coding practices. A
link should be a link. A rose should be a rose. And href="#" is just bad
practice IMO.
Addendum: I see that you later discourage that practice.

8- IMO, you do not sufficiently explain why href="javascript:..." is
bad. May I recommend some of the reasons listed here:
http://developer.mozilla.org/en/doc...D.22javascript:window.open.28....29.22_....3E

9- In your "Detecting Browser Versions" section, you may want to give
more references:
- Browser identification approach (aka "browser sniffing"): not best,
not reliable approach
http://www.mozilla.org/docs/web-developer/upgrade_2.html#BrowserIdent
- Using Object/Feature detection approach: best and overall most reliable
http://www.mozilla.org/docs/web-developer/upgrade_2.html#ObjectFeatDetect
- Browser detection - No; Object detection - Yes by Peter-Paul Koch
http://www.quirksmode.org/js/support.html
- Browser Detection and Cross Browser Support (in particular, sections 5
and 6):
http://developer.mozilla.org/en/docs/Browser_Detection_and_Cross_Browser_Support

10-
"The rules for using document.all are
2. Only fall back to using document.all as a last resort
3. Only use it if you need IE 5.0 support or earlier "
but IE 5.0 supports getElementById. The only possible reason to use
document.all is if you absolutely need to code for IE 4.x. And why would
you want to do some DHTML which would (could possibly) work in IE 4.x?
I don't see a reason for using document.all anymore.

Regards,

Gérard
 
R

RobG

Matt said:
http://www.JavascriptToolbox.com/bestpractices/

I started writing this up as a guide for some people who were looking for
general tips on how to do things the 'right way' with Javascript.
[...]

Have you thought of putting it up as a wiki? That way contributors
build your 'best of' site for you - it might get quite extensive though!

It would be good to have some 'best practice' examples or stubs for
various things - form validation, dynamic HTML stuff getting xml files,
calendars and date pickers, etc. - rather than a plethora of sites with
half-baked solutions.

[...]
 
M

Michael Winter

On 11/10/2005 07:02, Gérard Talbot wrote:

[snip]
1- I think you should start with something as basic as explaining that
document.all is bad, wrong, deprecated, obsolete, etc..

But the all collection is neither bad nor wrong. It can be argued that
it is largely redundant, but even in IE5.x is has a useful purpose
(though not IE6).
2- The web standards way to reference a form input element is:

document.forms.namedItem("formname").elements.namedItem("inputname")

What Matt wrote is just as 'compliant'. Read the ECMAScript bindings. It
also benefits from better support (so it is better in itself).
3- "All forms should have a name attribute. Referencing forms using
indexes, such as document.forms[0] is bad practice."
name attribute for form was dropped in XHTML specification.

So? What's that got to do with anything?

If NN4 (and the like) aren't a consideration (and they needn't be for
client-side form validation), then use an id attribute, or pass
references directly and omit an identifier entirely. However, if a name
attribute is necessary, then use it.
4- <form name="myform">
<input type="text" name="val1" value="1">
<input type="text" name="val2" value="2">
</form>
will trigger a validation markup error with a DTD strict.

If you're writing to an XHTML Strict DTD, but that is arguably worse
than reasonable defiance of the DTD.
5- "To fix this problem, Javascript needs a hint to tell it to treat the
values as numbers, rather than strings. Subtracting 0 from the value
will force javascript to consider the value as a number, and then using
the + operator on a number will perform addition, rather than
concatenation."

I would recommend the unary plus (+) operator instead.
I think you may be in fact teaching a wrong trick. What's wrong with
offering to use parseInt(strValParam, indexParam) to achieve exactly
what you want to achieve...

It's overkill in most cases. The value should have been validated
already, so all that's necessary is to convert the value which the unary
plus operator does very well.

The parseInt function can be very useful when using it to simultaneously
strip non-numeric trailing characters and convert, such as with CSS
length values.
6- "This is why 'return false;' is often included at the end of the code
within an onClick handler."
I would remove that sentence. The sentence does not perfectly make
sense.

It makes perfect sense when taken in context.
Also, we have no idea what the doSomething() function does exactly...

You do know that it's just an example, don't you. :p
7- "Often, links will just contain href="#" for the sake of simplicity,
when you know for sure that your users will have javascript enabled."
This is what a lot of people denounce also as bad coding practices.

It's bad practice when that's used outside the scope of a script.
However, if a script generates such a link, then it's not an issue. I
believe that's what Matt was aiming at (notice, 'know for sure'), but
perhaps it should be emphasised as the caveat might not be noticed.

[snip]

I haven't really read the document yet. I'll get around to it at some
point... :)

Mike
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Tue, 11 Oct 2005
02:02:23, seen in Gérard Talbot
Matt Kruse a écrit :

It will no doubt encourage a bloated programming style.

5- "To fix this problem, Javascript needs a hint to tell it to treat the
values as numbers, rather than strings. Subtracting 0 from the value
will force javascript to consider the value as a number, and then using
the + operator on a number will perform addition, rather than
concatenation."
I think you may be in fact teaching a wrong trick. What's wrong with
offering to use parseInt(strValParam, indexParam) to achieve exactly
what you want to achieve... which is converting a string into an integer
or to use parseFloat(strValParam).

Does unary + not work in the circumstances?

Note that if the actual parameter is a number already, unary + is
essentially a no-op, whereas parseInt will cause a conversion to String
(perhaps 1e+21) and a conversion of that to integer Number, with results
maybe not as intended.

X = 987654321987654321987654321
Z = parseInt(X) // Z = 9
 
R

Randy Webb

Matt Kruse said the following on 10/10/2005 11:06 PM:
http://www.JavascriptToolbox.com/bestpractices/

I started writing this up as a guide for some people who were looking for
general tips on how to do things the 'right way' with Javascript. Their code
was littered with document.all and eval, for example, and I wanted to create
a practical list of best practices that they could easily put to use.

The above URL is version 1.0 (draft) that resulted. IMO, it is not a
replacement for the FAQ, but a more practical guide for fixing some of the
problems that commonly get pushed into web sites.

Any comments?

<quote>
Otherwise, it's always a good idea to put a local fall-back page that
will be loaded for users without it disabled
</quote>

"for users with it disabled"

The "What not to do" section on anchors should have a note - or maybe a
seperate page - that explains why you shouldn't do those things.
Including, but not limited, to the negative impacts they can have.

document.all in IE

<quote>
Only use it if you need IE 5.0 support or earlier
</quote>

IE5.0, IIRC, supports gEBI so it should be priort to 5.0

Also, somewhere in there, some type of paragraph or so on innerHTML and
some of it's inherent strength's and weaknesses.

The only major problem with the whole page is the last few lines about
using Libraries which I totally disagree with. A newbe shouldn't be
using tools that they don't understand and the whole page seems to be
geared to some of the newbe mistakes that we were all guilty of
committing at times (and I still do it myself occassionaly).

Libraries are a personal choice and to me people should understand
enough about the language to know when to use a Library not just how to
use it. If all a person ever learns is that if they do this:

DynWrite('someDiv',someHTML);

That the page changes then they never learn and understand the inherent
problems with DynWrite itself (which it does have) and that function
comes straight from the FAQ itself for this group.

Sidenote: The major problem with innerHTML is when the string being
assigned is plain text. innerHTML has been proven, repeatedly, to be
considerably slower that DOM methods or even the IE proprietary
innerText property.





--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Answer:It destroys the order of the conversation
Question: Why?
Answer: Top-Posting.
Question: Whats the most annoying thing on Usenet?
 
R

Randy Webb

Dr John Stockton said the following on 10/11/2005 4:09 PM:
JRS: In article <[email protected]>, dated Tue, 11 Oct 2005
02:02:23, seen in Gérard Talbot



It will no doubt encourage a bloated programming style.

Before babbling nonsense like that you should, at minimum, at least read
and be familiar with what you are babbling about.

But, where is *your* guide to best practices?
 
G

Gérard Talbot

Michael Winter a écrit :
On 11/10/2005 07:02, Gérard Talbot wrote:

[snip]
1- I think you should start with something as basic as explaining that
document.all is bad, wrong, deprecated, obsolete, etc..


But the all collection is neither bad nor wrong. It can be argued that
it is largely redundant, but even in IE5.x is has a useful purpose
(though not IE6).

Useful purpose for IE 5.x? Can you elaborate on this? what do you mean...
What Matt wrote is just as 'compliant'. Read the ECMAScript bindings. It
also benefits from better support (so it is better in itself).

Better support? Yes, it's possible. I just mentioned a purely web
standards (DOM 2 HTML) way in there. That's all.
3- "All forms should have a name attribute. Referencing forms using
indexes, such as document.forms[0] is bad practice."
name attribute for form was dropped in XHTML specification.


So? What's that got to do with anything?

What I was suggesting here is that one can not declare, just like that,
that document.forms[0] is a bad practice when it is a DOM 2 HTML valid
practice in XHTML
and when what you formally recommend implies an invalid (markup code)
practice in XHTML.

Just compare the following 2 quotes/statements:

"All forms should have a name attribute." Matt K.

"HTML 4 defined the name attribute for the elements a, applet, form,
frame, iframe, img, and map. (...) in XHTML 1.0, the name attribute of
these elements is formally deprecated, and will be removed in a
subsequent version of XHTML."
http://www.w3.org/TR/2002/REC-xhtml1-20020801/#h-4.10
If NN4 (and the like) aren't a consideration (and they needn't be for
client-side form validation), then use an id attribute, or pass
references directly and omit an identifier entirely. However, if a name
attribute is necessary, then use it.

Yes, id attribute is another way. name attribute can not be the only way
since it implies invalid markup code in XHTML.
If you're writing to an XHTML Strict DTD, but that is arguably worse
than reasonable defiance of the DTD.

Well, what if I am writing in HTML 4.01 strict then? The above code will
be reported as invalid markup by validators. I am repeating myself here.
I would recommend the unary plus (+) operator instead.



It's overkill in most cases. The value should have been validated
already, so all that's necessary is to convert the value which the unary
plus operator does very well.

I don't agree with you. parseInt function original purpose (specific
purpose, defined task) is to parse a string and convert it into
integers. Isn't it what Matt Kruse' code wanted to specifically achieve
to begin with?
+ is an overloaded operator; it's not even a function.

The parseInt function can be very useful when using it to simultaneously
strip non-numeric trailing characters and convert, such as with CSS
length values.



It makes perfect sense when taken in context.

I disagree. It does not make sense within the context, as written
in the document. We have no idea what doSomething() function actually does.
You do know that it's just an example, don't you. :p

The provided code is an abstract example. It's not a defined example.
It's not a concrete example, serving a specified purpose.

This page:
https://bugzilla.mozilla.org/attachment.cgi?id=111215
(from bug 44449 at bugzilla)
is a concrete example showing and testing a precise issue.

This example:
http://developer.mozilla.org/en/docs/DOM:window.open#Best_practices
is a whole concrete example showing, demontrating, accomplishing a
precise, concrete goal, task.

There is no general rule for returning false in a script, in an onclick
event attribute. It all depends on what a script actually does within a
real-live webapge context. The Matt K. document suggests otherwise.

It's bad practice when that's used outside the scope of a script.

I'm sorry: I disagree. It's *_always_* a bad practice in my opinion.
href="#" should never be used anywhere.
Matt K. discourage href="#" but not to the level I would.
However, if a script generates such a link, then it's not an issue.

.... then a real button describing the purpose of the script should be
used, not a link. A rose is a rose is a rose. A link should be a real
link should be a real link. And a script modifying a DOM tree or a
document structure should be described as such.

"Links that don't behave as expected undermine users' understanding of
their own system. A link should be a simple hypertext reference that
replaces the current page with new content"
J. Nielsen

[snip]

I haven't really read the document yet.

Well, then, maybe it would be a good idea to do so.
I'll get around to it at some
point... :)

Mike

Gérard
 
M

Michael Winter

On 12/10/2005 04:56, Gérard Talbot wrote:

[The all collection]
Useful purpose for IE 5.x? Can you elaborate on this? what do you
mean...

The getElementsByTagName method is not implemented properly in IE5.x.
Passing an asterisk (*) will always return an empty collection, rather
than one that contains all descendants of the node. The most reasonable
solution is to detect this failure and use the all collection in place.

[Using the namedItem methods of collections, rather than square brackets]
Better support? Yes, it's possible.

It's guaranteed.
I just mentioned a purely web standards (DOM 2 HTML) way in there.
That's all.

Using square brackets /is/ a 'purely web standards [...] way'.

[The name attribute in XHTML]
What I was suggesting here is that one can not declare, just like that,
that document.forms[0] is a bad practice when it is a DOM 2 HTML valid
practice in XHTML

Unless one is iterating through a collection, using numeric indices is
not a recommended practice as changes to markup mandate a change to the
script, whereas using some form of identifier (or direct reference,
which is what I really recommend) does not.
and when what you formally recommend implies an invalid (markup code)
practice in XHTML.

As you were told in ciwah, validation is not a goal in itself. There can
be justified reasons for writing invalid markup[1], and using the name
attribute is not going to break a browser if you truly understand how
browsers will be treating the markup. After all, they won't be parsing
the document as XHTML anyway, so use that notation is, at most,
superficial use of an XML-based language. You would be better off
abandoning XHTML as an output format for the time being (for several
years, at least) and using HTML. That is a better use of your time than
worrying about a single attribute.

[snip]
[snip]

Well, what if I am writing in HTML 4.01 strict then? The above code
will be reported as invalid markup by validators.

For a different reason, yes, which has nothing to do with what we've
just been discussing.

There is no reason to omit the action attribute in actual markup, but
again this is an example to illustrate an entirely unrelated concept;
potential conflicts between concatenation and addition.

[snip]
[The parseInt function is] overkill in most cases. The value should
have been validated already, so all that's necessary is to convert
the value which the unary plus operator does very well.

I don't agree with you. parseInt function original purpose (specific
purpose, defined task) is to parse a string and convert it into
integers.

If the string has been validated as a number, which it should have been,
then the only operation that is needed is conversion. The sole purpose
of the unary plus operator is to convert its operand to a number. The
parseInt function, on the other hand, parses only to an integer -
totally different and often not as useful.
Isn't it what Matt Kruse' code wanted to specifically achieve
to begin with?

No. Matt describes string to number conversion, not string to integer.
+ is an overloaded operator; it's not even a function.

The addition operator and the plus (+) symbol itself is overloaded. The
unary plus operator is not. That the latter isn't a function is utterly
irrelevant.

[snip]
[snip]

I disagree. It does not make sense within the context, as written
in the document. We have no idea what doSomething() function actually does.

It doesn't matter what that function does. Matt is demonstrating event
cancellation (specifically, cancelling link navigation). Anything could
be placed before the return statement, including a comment like

/* Some code here */

[snip]
There is no general rule for returning false in a script, in an onclick
event attribute.

No, there isn't, but Matt isn't defining a general rule. The heading of
[snip]

I'm sorry: I disagree. It's *_always_* a bad practice in my opinion.

In markup, I agree with you absolutely, and I wouldn't use it in a
script, either; I wouldn't use a link that's not a link.

The reason why a "#" href attribute value is frowned upon is because is
doesn't do anything. If the script cannot act, for whatever reason, the
user is left with a link that doesn't do anything. This is contrary to
what a link implies. If the script generates the link, and the link's
scripted action can be /guaranteed/ to work, then the usability issue
doesn't imply. The argument now is just whether it's appropriate to use
a link at all.
Well, then, maybe it would be a good idea to do so.

I had neither the time, nor the inclination last night to read
through that document and possibly draft my own response. However, I
thought your post needed commenting upon as I felt parts of it were
suggesting changes that were misguided.

Mike


[1] I don't believe that structurally invalid markup is acceptable,
but certain minor violations /can/ be justified. However, I do
advocate that authors should learn and practice writing valid
documents whenever possible.
 
M

Matt Kruse

Gérard Talbot said:
What I was suggesting here is that one can not declare, just like
that, that document.forms[0] is a bad practice when it is a DOM 2
HTML valid practice in XHTML
and when what you formally recommend implies an invalid (markup code)
practice in XHTML.

XHTML sucks :)
In reality, most people don't need to consider it, and anyone being forced
to use XHTML surely is not looking for the basic level of suggestions that I
included in my document.

If you include every exception and side-notes about every other way of doing
things, the document becomes huge and unreadable to most average users who
just want a few hints on how to do things better.
Well, what if I am writing in HTML 4.01 strict then? The above code
will be reported as invalid markup by validators. I am repeating
myself here.

It's an abbreviated example to show the point. It is not intended to be
full, correct markup.
I'm sorry: I disagree. It's *_always_* a bad practice in my opinion.
href="#" should never be used anywhere.

Well, then we disagree. I use href="#" all the time within web apps that
require javascript. Especially when there are hundreds of links on a page,
having each one contain a useless href is pointless, when the user is known
to have javascript enabled. You're welcome to write and publish your own
Best Practices document :)
 
M

Matt Kruse

Randy said:

I've corrected a few of the things you've suggested. Thanks!
The only major problem with the whole page is the last few lines about
using Libraries which I totally disagree with. A newbe shouldn't be
using tools that they don't understand...

The use of "libraries" will always be a debate among regulars of this group.

My take has always been that it would be fantastic if everyone could
understand javascript well enough to write their own widgets when they need
them, or at least pick the best ones of those available.

But _reality_ is something different. Most people don't want to learn a lot
about javascript, or don't have time to implement a generalized
cross-browser solution to some problems. I've received hundreds if not
thousands of thank-you's from people saying things like "I needed to add a
calendar popup in my project at work, and I had almost no time left. I
implemented yours in literally 10 minutes and it works perfectly. Thank you
so much!" I think libraries are important for situations like that, and also
for situations where users know what they want but don't have the expertise
to implement it. A person need not be an expert in everything in order to
use the tools available.

A javascript "library" is simply a packaged solution with an
easily-understood interface. We all use those all the time. I bet you aren't
telneting to your news server and issuing NNTP commands by hand, are you?
You're using a higher-level tool so that you don't _have_ to understand the
NNTP protocol. If you have to understand the inner-workings of every tool
you use daily, you could never accomplish anything. Using libraries and
higher-level tools is essential to being more creative and building bigger
and better solutions.

If a javascript library is implemented well enough, with a good interface,
with not a lot of extra code, then I don't see any reason not to use it or
recommend that others use it. I know others disagree, and that's fine. But I
won't be convinced any time soon. Especially when I get thousands of
visitors to my libraries each day, many thank-you emails each month, and
donations from companies and individuals whose projects and timelines were
saved because they found a packaged solution to a common problem that they
could implement in minutes rather than hours or days. And _especially_ when
many of the "anti-library" folks don't offer feasible alternatives for
people faced with challenges that are easily solved by using a decent
library :)
 
M

Michael Winter


"Square Bracket Notation"

You might want to note the different restrictions that both forms have.
That is, the token that forms each part of the dot notation property
accessor must conform to the Identifier production, whereas property
names used with square brackets have no such restrictions. However, the
expression within the brackets will /always/ be type-converted to a string.

This might also be a good time to follow on and dispel the idea about
hash 'arrays'.

I don't know about always using square bracket notation.


"Referencing Forms And Form Elements"

Further to Gérard's complaint, it might be better to refer abstractly to
form identifiers (as both the name and id attributes are supposed to be
unique identifiers), unless the author is referring to the form through
an event listener in which case no identifier is needed.


"Problems With Concatenation"

+theform.elements["val1"].value + +theform.elements["val2"].value

I think it's better to use parentheses around the unary expression,
especially with the right-hand operand above.

It might be better to reference the elements collection directly, rather
than the form (at least when you aren't dealing with the form itself).

var controls = document.forms.myForm.elements,
total = +controls.val1.value + (+controls.val2.value);


"Getting And Setting Form Values"

"[Using unified functions for] forms with only 1 radio button
in a group [...]"

A singular radio button should never exist. If the document is generated
server-side (surely the only reason this situation could occur), that
form control should be removed and the served script altered to only
deal with a single control.

Mike
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Tue, 11 Oct
2005 23:15:34, seen in Randy Webb
Sidenote: The major problem with innerHTML is when the string being
assigned is plain text. innerHTML has been proven, repeatedly, to be
considerably slower that DOM methods or even the IE proprietary
innerText property.

Which in the majority of cases is totally unimportant. Since the aim is
to change the information presented to the mind of the user, the time
taken is usually significant only if it exceeds about 200 ms.

My Holidays page computes and writes a whole annual holidays table
(about 1.5 windows high) covering 6 years, using DynWrite, in a
perceptible fraction of a second, on a 300 MHz PII. That's good enough.
 
G

Gérard Talbot

Michael Winter a écrit :
On 12/10/2005 04:56, Gérard Talbot wrote:

[The all collection]
Useful purpose for IE 5.x? Can you elaborate on this? what do you
mean...


The getElementsByTagName method is not implemented properly in IE5.x.
Passing an asterisk (*) will always return an empty collection,

I didn't know that.

rather
than one that contains all descendants of the node. The most reasonable
solution is to detect this failure and use the all collection in place.


Using square brackets /is/ a 'purely web standards [...] way'.

[The name attribute in XHTML]
What I was suggesting here is that one can not declare, just like that,
that document.forms[0] is a bad practice when it is a DOM 2 HTML valid
practice in XHTML


Unless one is iterating through a collection, using numeric indices is
not a recommended practice

Matt K. explicitly states that numeric indices is a bad practice.
"Referencing forms using indexes, such as document.forms[0] is bad
practice."

as changes to markup mandate a change to the
script, whereas using some form of identifier (or direct reference,
which is what I really recommend) does not.
and when what you formally recommend implies an invalid (markup code)
practice in XHTML.


As you were told in ciwah, validation is not a goal in itself. There can
be justified reasons for writing invalid markup[1],

I don't recall being told that.

and using the name
attribute is not going to break a browser if you truly understand how
browsers will be treating the markup. After all, they won't be parsing
the document as XHTML anyway, so use that notation is, at most,
superficial use of an XML-based language. You would be better off
abandoning XHTML as an output format for the time being (for several
years, at least) and using HTML.

A document about javascript best practices can not and should not rule
out/exclude people who serve XHTML document as application/xhtml+xml.
Otherwise, at the very least, the document should then state that it is
intended for HTML based documents only.
That is a better use of your time than
worrying about a single attribute.


Somehow the tone of your post has become personal. All my posts were
referring to the draft document.

I never used more than 2 forms in a single page. Most of the time, I
only have 1. So what's the big deal with numeric indice?
All I can read in the document is a simple directive in the document
regarding numeric indice: no explanation as to why such directive and no
recommended solution for XHTML-based documents.

It wouldn't take a lot of words to compensate for these 2 issues...
[snip]
4- <form name="myform">
<input type="text" name="val1" value="1">
<input type="text" name="val2" value="2">
</form>

[snip]

Well, what if I am writing in HTML 4.01 strict then? The above code
will be reported as invalid markup by validators.


For a different reason, yes, which has nothing to do with what we've
just been discussing.

When should someone bring this up then? When a "HTML Best Practices"
document is released? Writing valid markup code should always be the norm.
There is no reason to omit the action attribute in actual markup, but
again this is an example to illustrate an entirely unrelated concept;
potential conflicts between concatenation and addition.

This example is not just an isolated chunck of code in an ordinary
webpage. Matt K. actually wants people to follow such example and other
examples as well. So why not make it perfectly valid then?

<form name="myform" action="">
<p>
<input type="text" name="val1" value="1">
<input type="text" name="val2" value="2">
</p>
</form>

It takes a grand total of an extra 20 characters to fullfil the validity
requirements. What's so difficult here?
[snip]
[The parseInt function is] overkill in most cases. The value should
have been validated already, so all that's necessary is to convert
the value which the unary plus operator does very well.


I don't agree with you. parseInt function original purpose (specific
purpose, defined task) is to parse a string and convert it into
integers.


If the string has been validated as a number, which it should have been,
then the only operation that is needed is conversion. The sole purpose
of the unary plus operator is to convert its operand to a number. The
parseInt function, on the other hand, parses only to an integer -
totally different and often not as useful.

Ok, what about parseFloat() then? I mentioned it in my original post.
No. Matt describes string to number conversion, not string to integer.



The addition operator and the plus (+) symbol itself is overloaded. The
unary plus operator is not. That the latter isn't a function is utterly
irrelevant.

IMO, tricks based on + and -0 can not be the best recommendable way to
convert a string to a number. parseInt or parseFloat should be used instead.

One example: Javascript Bible 4th edition by D. Goodman on "Converting
strings to numbers" p.78-79. Not one word on + and - tricks: everything
in his words clearly refers to the use of parseInt and of parseFloat. Is
he way off the fact and the matter?

[snip]
6- "This is why 'return false;' is often included at the end of the
code within an onClick handler."

[snip]

I disagree. It does not make sense within the context, as written
in the document. We have no idea what doSomething() function actually
does.


It doesn't matter what that function does. Matt is demonstrating event
cancellation (specifically, cancelling link navigation). Anything could
be placed before the return statement, including a comment like

/* Some code here */

[snip]
There is no general rule for returning false in a script, in an onclick
event attribute.


No, there isn't, but Matt isn't defining a general rule. The heading of
the section is "Using onClick in <A> tags", and returning false in that
context is well-defined.

Ok. Let me repeat what you've said so that no one gets you wrong. You
say Matt K. in that document is not defining a general rule regarding
the use of returning false in an onclick even attribute.

7- "Often, links will just contain href="#" for the sake of
simplicity, when you know for sure that your users will have
javascript enabled."

[snip]

I'm sorry: I disagree. It's *_always_* a bad practice in my opinion.


In markup, I agree with you absolutely, and I wouldn't use it in a
script, either; I wouldn't use a link that's not a link.

The reason why a "#" href attribute value is frowned upon is because is
doesn't do anything. If the script cannot act, for whatever reason, the
user is left with a link that doesn't do anything. This is contrary to
what a link implies. If the script generates the link, and the link's
scripted action can be /guaranteed/ to work, then the usability issue
doesn't imply. The argument now is just whether it's appropriate to use
a link at all.

Right. I say that a link should be a link, should look like a link,
should act like a link. Otherwise, a button should be used with a proper
caption, text describing its action. It's about proper use of markup,
semantics.

[snipped]
[1] I don't believe that structurally invalid markup is acceptable,
but certain minor violations /can/ be justified. However, I do
advocate that authors should learn and practice writing valid
documents whenever possible.

If a document aspires to promote good, recommendable, sound coding
practices, then its constructed examples should first of all practice
the document's intended goals, should be a model.

Gérard
 
G

Gérard Talbot

Matt Kruse a écrit :
Gérard Talbot said:
What I was suggesting here is that one can not declare, just like
that, that document.forms[0] is a bad practice when it is a DOM 2
HTML valid practice in XHTML
and when what you formally recommend implies an invalid (markup code)
practice in XHTML.


XHTML sucks :)
In reality, most people don't need to consider it, and anyone being forced
to use XHTML surely is not looking for the basic level of suggestions that I
included in my document.

I think it would be fair to indicate to all readers of that page that
your best practices are for HTML documents only, then.
If you include every exception and side-notes about every other way of doing
things, the document becomes huge and unreadable

This is exaggerated.

to most average users who
just want a few hints on how to do things better.




It's an abbreviated example to show the point. It is not intended to be
full, correct markup.

But people don't know that. And newbies can not and will not know that.
The web is litterally full of webpages where examples were tried, were
trusted, copied and pasted. Dynamicdrive.com and other javascript
copy-N-paste are full of examples of dubious quality, poor coding
practices and invalid markup code.

It wouldn't take a lot more typing to correct this. Writing valid markup
code shouldn't be a luxury in your document. Just consider what your
document aspires to present: javascript best practices.
Well, then we disagree. I use href="#" all the time within web apps that
require javascript. Especially when there are hundreds of links on a page,
having each one contain a useless href is pointless, when the user is known
to have javascript enabled. You're welcome to write and publish your own
Best Practices document :)

WCAG groups and J. Nielsen have already written on this whole issue.
A script triggered by an onclick event handler in a link should not do a
lot more than a plain vanilla link does otherwise you're not using a
link for its intended purpose to begin with. In such case, you may be
misusing the <a> element; a <button type="button"
onclick="doSomething();"> would most likely be better markup usage,
better semantic.

You never gave an example of what doSomething() would be about, could
do. So, the doSomething() example is not concrete, not demonstrating a
possible good usage, etc. The doSomething() example is promoting a
general use of canceling the return value.

Gérard
 
R

Richard Cornford

Matt said:
Randy said:

I've corrected a few of the things you've suggested. Thanks!
The only major problem with the whole page is the last few lines
about using Libraries which I totally disagree with. A newbe
shouldn't be using tools that they don't understand...

The use of "libraries" will always be a debate among
regulars of this group.

It isn't debated that much, the only people who seem to argue in favour
of libraries are individuals who have libraries to promote. It seems
that the vested interest and unwillingness to abandon the time already
invested tends to encourage intransigence. When we have the debate the
majority of expressed opinion has always been against the use of
monolithic generalised libraries as an inappropriate concept in browser
scripting.
My take has always been that it would be fantastic if
everyone could understand javascript well enough to
write their own widgets when they need them, or at least
pick the best ones of those available.

But _reality_ is something different. Most people don't want
to learn a lot about javascript, or don't have time to
implement a generalized cross-browser solution to some problems.

It is perverse to state this in the context of a request for comments on
a document that asserts that its subject is "best Practices". Here you
are arguing for expedience, but "best practice" most definitely is about
ideals that should be aspired to and not short term expedience.
I've received hundreds if not thousands of thank-you's from
people saying things like "I needed to add a calendar popup
in my project at work, and I had almost no time left.
I implemented yours in literally 10 minutes and it works
perfectly. Thank you so much!"

So a developer who either could not write the code they had undertaken
to create, or could not accurately/effectively schedule their tasks gets
to conceal their incompetence form their employer while reducing the
viability (and so potential profitability) of whatever they have
created? Yes, I can see widespread appeal for having that facility, it
still doesn't make it a good idea.

... , and donations from companies and individuals whose ...
<snip>

So your public support for libraries in general, and repeated promotion
of your own libraries, is not without some financial motivation, and
direct returns? I am reminded of Ira Baxter, who, in the face of
widespread explanations of why javascript obfuscation is worthless,
still maintains that it is a valuable practice, and then references
people to the javascript obfuscateor that her employers sell.

Anyway, to the "best practices" page; What I like to see when someone
proposes something as a "best practice" is an explanation of why it
might be considered a best Practice. Without that the assertion has only
the weight of the individual who is making the assertion, and needs
filtering through an appreciation of the personal prejudices (and vested
interests of) the individual in question. With an explanation of why
something could be regarded as a best practice it is possible to asses
the proposal on the merits of the argument made for it. So, for example,
when Gérard Talbot proposes:-

document.forms.namedItem("formname").elements.namedItem("inputname")

- as, in some sense, a "best practice" (or "correct practice") in
accessing form controls, and supports that assertion with the
justification:-

"The web standards way to reference a form input element is:"

- it is possible to assess the suggestion on the basis of its
justification. And observe that the proposal is no more (and no less)
"web standards" than the more ECMAScript-style and more cross-browser:-

document.forms["formname"].elements["inputname"]

That is, because there was a justification for the assertion it is
possible to determine with certainty that it is bogus. Any practice
proposed with a justification that cannot be as easily dismissed stands
a much better chance of qualifying as a "best practice".

Your page makes no justifications for the items it proposes as "best
practice" and so is reduced to a sequence of personal assertions. And
some of them are distinctly odd in context. For example, you propose
that people use bracket notation, seemingly to the exclusion of dot
notation (insane as that would be). I am not even sure that using
bracket notation qualifies as a "practice" (in the sense of "best
practice") at all. The best that can be said of bracket notation in the
direction of "best practice" is that it should not be disregarded when
using property accessors (particularly in favour of eval). But that is
really just proposing that it is "best practice" to be familiar with the
constructs, syntax, and behaviour of the language you are writing in
(which is a bit too obvious an assertion to have been explicitly stated
in any code authoring standards document that I have read to date).

Without any justification for the proposed "best practices", and so
their reduction to the status of personal assertions, it is interesting
to note the number of links in the page to technical articles written by
others. That seems almost a rhetorical ploy; the quality of the advice
given on the page is bolstered by the quality of the material referenced
from the page.

On the whole your page is too superficial to justify its title, and the
items covered are more reminiscent of a trivial FAQ than what it
purports to be. Much that is widely held to be "best practice", in
javascript or in programming in general is not mentioned at all. For
example, the formal structuring and block indenting of development code
(and the imposition of a single style of such formatting within
organisations) is certainly a "best practice", but gets no mention.

On the other hand, given your record of unusual applications of meaning
to English statements perhaps the inappropriate title is just another
manifestation of that.

Richard.
 
R

Richard Cornford

Gérard Talbot said:
Michael Winter a écrit :
On 12/10/2005 04:56, Gérard Talbot wrote:

[The all collection]
Useful purpose for IE 5.x? Can you elaborate on this? what do you
mean...


The getElementsByTagName method is not implemented properly in IE5.x.
Passing an asterisk (*) will always return an empty collection,

I didn't know that.

This should not be particularly surprising as the '*' wildcard for tag
names is not mentioned in the W3C Core DOM Level 1 standard, and IE 5
was (at best) a DOM Level 1 browser. This is also true for Opera <= 6
and NetFront 4, for example.

IMO, tricks based on + and -0 can not be the best recommendable

They are not tricks, they are just type-conversion. An aspect of a
loosely-typed language that authors need to appreciate. If forced
type-conversion is wanted only two constructs can be recommenced; Unary
+, because it is the fastest technique (so the best to use when speed
matters) and passing the numeric string as the argument to the -
Number - constructor called as a function, because it is
self-documenting (and so should be used when clarity of source code is
desired).

It is often proposed that when Unary + is used the unary expression
should be parenthesised so that the + symbol is not easily mistaken for
addition/concatenation or typoed pre and post increment.
way to convert a string to a number. parseInt or parseFloat
should be used instead.

Apart from their unexpected treatment of some forms of input (which
should be precluded with regular expression validation of numeric
strings where there is doubt) parseFloat and parseInt are the slowest
method of turning a string into a number and less self-documenting than
the use of the Number constructor (though javascript authors should be
familiar enough with them for that not to be a real problem).
One example: Javascript Bible 4th edition by D. Goodman on
"Converting strings to numbers" p.78-79. Not one word on +
and - tricks: everything in his words clearly refers to the
use of parseInt and of parseFloat.
Is he way off the fact and the matter?

Danny Goodman is so 'way off' that the best advice would be to burn his
books unread. He has done enough harm to javascript authoring already.

Richard.
 
G

Gérard Talbot

Dr John Stockton a écrit :
JRS: In article <[email protected]>, dated Tue, 11 Oct
2005 23:15:34, seen in Randy Webb



Which in the majority of cases is totally unimportant. Since the aim is
to change the information presented to the mind of the user, the time
taken is usually significant only if it exceeds about 200 ms.

The question remains though: what's the *best practice* (for beginners,
intermediate users, etc) when the string being assigned is plain text.
Most of us will grant you that the gain in time is negligeable if the
string is short and if the user system resources are considerable.
When is it best to use innerHTML? When is a DOM method a better choice
over innerHTML?

This page:
innerHTML VS DOM.
http://www.developer-x.com/content/innerHTML/default.html
suggests there are more problems with usage of innerHTML.

Gérard
 
M

Michael Winter

Michael Winter a écrit :
[snip]
Unless one is iterating through a collection, using numeric indices is
not a recommended practice

Matt K. explicitly states that numeric indices is a bad practice.
"Referencing forms using indexes, such as document.forms[0] is bad
practice."

And I'm saying more-or-less the same thing. Just less strongly.

[snip]
As you were told in ciwah, validation is not a goal in itself. There can
be justified reasons for writing invalid markup[1],

I don't recall being told that.

Which part?

You certainly were told the former in the recent '3 questions on
validation' thread. For instance, the first response by Travis Newbury:

You seem to have missed the point that validation is a "tool" not
a "goal"
-- Travis Newbury,
<[email protected]>

I'm saying the latter now, though others have in other discussions. So
did Jukka in his article, '"HTML validation" is a good tool, but just a
tool'[1], which he referenced in the same thread as the quote above.

[snip]
A document about javascript best practices can not and should not rule
out/exclude people who serve XHTML document as application/xhtml+xml.

Serving a non-trivial script with a document served as
application/xhtml+xml is often a completely different kettle of fish as
the objects models are different, and would warrant its own document.
Anyway, if an author is knowledgeable enough to correctly
content-negotiate a document, then they should know enough to correctly
transfer remarks about HTML to XHTML.
Somehow the tone of your post has become personal. All my posts were
referring to the draft document.

My apologies. That sentence wasn't directed at you. It was the sloppy
use a of second-person pronoun meant generically in text that used the
fourth-person in that situation, more often than not. The word, "your",
should have been "one's".

[snip]
So what's the big deal with numeric indice?

It isn't a 'big deal', but an identifier is immune to markup changes
whereas an index may not be. But still, and I reiterate (again), I'd
recommend using element references wherever possible and avoid the issue
entirely.
All I can read in the document is a simple directive in the document
regarding numeric indice: no explanation as to why such directive and no
recommended solution for XHTML-based documents.

If an author wants to write valid XHTML markup, but needs to be told to
use an id attribute in place of a name attribute (or see above), I think
the author may need a career change.

[A missing action attribute]
When should someone bring this up then? When a "HTML Best Practices"
document is released?

Forms are designed to be submitted. The action attribute is used to
specify where the data is sent. Ergo, an author is almost certainly
going to include one, anyway. I doubt that any reader of Matt's document
will stop just because he omitted it in a trivial example.

I have no problem with him including a dummy attribute value, but it
really isn't a big deal if he doesn't.

And yes, an 'HTML best practices' article would be more on-topic. :D

[Converting to number]
Ok, what about parseFloat() then? I mentioned it in my original post.

It still does more than necessary with no added advantages in return.

[snip]
IMO, tricks based on + and -0 can not be the best recommendable way to
convert a string to a number.

Subtracting zero is a trick, and I don't recommend it either. However,
the unary plus operator is not a trick.

The unary + operator converts its operand to Number type.
-- Section 11.4.6, ECMA-262 3rd Ed.
One example: Javascript Bible 4th edition by D. Goodman [...]

Danny Goodman is not a recommended author in this group and neither is
his book. I haven't read it, but from what I have seen from him, I'm
inclined to agree.

[snip]
Ok. Let me repeat what you've said so that no one gets you wrong. You
say Matt K. in that document is not defining a general rule regarding
the use of returning false in an onclick even attribute.

That is correct. That entire section of the article only refers to A
(anchor) elements. The references to 'link', 'anchor', or 'href' in the
first three paragraphs (of five), plus the heading and examples should
make that very clear.

[snip]

Mike


[1] "HTML validation" is a good tool, but just a tool
<URL:http://www.cs.tut.fi/~jkorpela/html/validation.html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top