By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,660 Members | 1,735 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,660 IT Pros & Developers. It's quick & easy.

Javascript Best Practices Document v1.0

P: n/a
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.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Oct 11 '05 #1
Share this Question
Share on Google+
136 Replies


P: n/a
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.name dItem("inputname")

http://www.w3.org/TR/DOM-Level-2-HTM...tml#ID-1689064

http://www.w3.org/TR/DOM-Level-2-HTM...ml#ID-21069976

http://www.w3.org/TR/DOM-Level-2-HTM...ml#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/docs.....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-deve...l#BrowserIdent
- Using Object/Feature detection approach: best and overall most reliable
http://www.mozilla.org/docs/web-deve...jectFeatDetect
- 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...rowser_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
--
remove blah to email me
Oct 11 '05 #2

P: n/a
Matt Kruse wrote:
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.

[...]

--
Rob
Oct 11 '05 #3

P: n/a
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.name dItem("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

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Oct 11 '05 #4

P: n/a
JRS: In article <3r************@uni-berlin.de>, dated Tue, 11 Oct 2005
02:02:23, seen in news:comp.lang.javascript, Gérard Talbot
<ne***********@gtalbot.org> posted :
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.

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

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Oct 11 '05 #5

P: n/a
Dr John Stockton wrote:
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.

It will no doubt encourage a bloated programming style.


Did you read it?

No? I didn't think so.

Your comments are worthless, as usual.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Oct 12 '05 #6

P: n/a
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?
Oct 12 '05 #7

P: n/a
Dr John Stockton said the following on 10/11/2005 4:09 PM:
JRS: In article <3r************@uni-berlin.de>, dated Tue, 11 Oct 2005
02:02:23, seen in news:comp.lang.javascript, Gérard Talbot
<ne***********@gtalbot.org> posted :
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.

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?

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 12 '05 #8

P: n/a
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...
2- The web standards way to reference a form input element is:

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

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.
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.


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.
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.


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.
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.


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

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...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.

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.


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
--
remove blah to email me
Oct 12 '05 #9

P: n/a
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]
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.

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]
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.
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.
I haven't really read the document yet.


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.

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Oct 12 '05 #10

P: n/a
Gérard Talbot wrote:
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 :)

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Oct 12 '05 #11

P: n/a
On 11/10/2005 04:06, Matt Kruse wrote:
http://www.JavascriptToolbox.com/bestpractices/


"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

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Oct 12 '05 #12

P: n/a
Randy Webb wrote:
[snip]
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 :)

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Oct 12 '05 #13

P: n/a
JRS: In article <28********************@comcast.com>, dated Tue, 11 Oct
2005 23:15:34, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :

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.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Oct 12 '05 #14

P: n/a
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="[url]">
<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.
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.


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
--
remove blah to email me
Oct 12 '05 #15

P: n/a
Matt Kruse a écrit :
Gérard Talbot wrote:
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.

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.


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.
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 :)


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
--
remove blah to email me
Oct 13 '05 #16

P: n/a
Matt Kruse wrote:
Randy Webb wrote:
[snip]
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.

<snip> ... , 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.name dItem("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.
Oct 13 '05 #17

P: n/a
Gérard Talbot wrote:
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.

<snip> 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.
Oct 13 '05 #18

P: n/a
Dr John Stockton a écrit :
JRS: In article <28********************@comcast.com>, dated Tue, 11 Oct
2005 23:15:34, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :
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.


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/i...L/default.html
suggests there are more problems with usage of innerHTML.

Gérard
--
remove blah to email me
Oct 13 '05 #19

P: n/a
On 13/10/2005 00:30, Gérard Talbot wrote:
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,
<11**********************@g43g2000cwa.googlegroups .com>

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.
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.


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>

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Oct 13 '05 #20

P: n/a
Richard Cornford wrote:
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 makes sense that if you favor an approach to development, that you would
have something to offer which takes that approach. Much the same way that
you 'promote' closures and offer documentation and example scripts using the
approach.
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.
Few would argue in favor of 'monolithic' generalised libraries. Libs with a
specific purpose and just a little extra 'code bloat' as some might call it
is a different story entirely. You often confuse the two.
Here
you are arguing for expedience, but "best practice" most definitely
is about ideals that should be aspired to and not short term
expedience.
The two goals are not mutually exclusive. A developer may need a short-term
solution, yet be interested in learning to do things the 'right' way
long-term.
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?
Ridiculous statement.
I've used many 3rd-party Java libraries which I certainly would not be able
to develop on my own. Yet I benefitted by being able to deliver more
advanced functionality in a shorter timeline.

You seem to argue in favor of writing everything of scratch, which is
absurd. You surely don't follow that reasoning yourself. You just define it
differently to suit your needs.
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 do not 'promote' my libraries. I offer them as solutions to specific cases
in this group where my already-developed solution matches exactly what the
poster needs. There is no financial motivation. There may be some financial
reward, but it is certainly not a motivating factor.
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.
This is a valid thought, and I had considered adding a "Why?" link which
would open up a pre-hidden DIV explaining in a little more detail the
rationale behind the recommendation.
Your page makes no justifications for the items it proposes as "best
practice" and so is reduced to a sequence of personal assertions.
As is any recommendation. Having a detailed justification doesn't make it
any more 'correct', and readers are still open to disagree with the
justification. Any 'truth' is only as good as your faith in the person
telling it to you. But philosophy is not really on topic...
For example, you propose
that people use bracket notation, seemingly to the exclusion of dot
notation (insane as that would be).
For any developer who doesn't know enough to decide for themselves to do
differently, I think it is the 'safest' recommendation. It will certainly
lead to fewer problems and less confusion for the average web developer.
On the whole your page is too superficial to justify its title


On the contrary, I've received great feedback so far from many others who
said they immediately benefitted from it.
Javascript is a mystery to many. A short, concise, easy to understand
document such as thing can be very valuable to those who may be experienced
programmers but just want a push in the right direction when it comes to
javascript. The FAQ is great, but it's too big, too long, and too bloated to
be scanned quickly in a lunch break by someone who wants to avoid typical
day-to-day JS problems.

For one who criticizes so much, I would expect to see your alternative 'Best
Practices' document offered on the web somewhere. It is conspicuously
absent.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Oct 13 '05 #21

P: n/a
Gérard Talbot said the following on 10/12/2005 7:52 PM:
Matt Kruse a écrit :


<snip>
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.


And is totally useless with JS disabled.......

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 13 '05 #22

P: n/a
Gérard Talbot wrote:
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.


I've updated a few places pointed out to be more 'correct', fwiw.
Well, then we disagree. I use href="#" all the time within web apps
that require javascript.

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.


So?

1) Using things for their intended purpose leads to less innovation. The web
wouldn't be where it is at now if people only used things for their
'intended purpose'.

2) Links are often preferred for triggering javascript functionality because
of design issues. For example, a DIV showing a list of matches to a
partially-filled input box may be <a> links which trigger a function to
populate the box. Having them as buttons would be ridiculous. And sometimes,
links just look and behave better.

3) J. Nielsen is not god. I think he's right on many points, and
ridiculously wrong on many points. I lose no sleep when he disagrees with
me.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Oct 13 '05 #23

P: n/a
Dr John Stockton said the following on 10/12/2005 4:59 PM:
JRS: In article <28********************@comcast.com>, dated Tue, 11 Oct
2005 23:15:34, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :
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.


Then why is it that with this code:

var s="10";
var t="12";
var total = Number(s) + Number(t);
alert(total);

That you are one of the first ones to point out:

"Don't convert Strings to Numbers that way, use the unary + because its
*faster*"

Either its speed or its "good enough". Whats the standard?
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.


And if you writing an entire holidays table then you are writing HTML
and not text so your comparison is irrelevant.

But that aside, the standard I have for myself is not to be "good
enough", it's to be the best that I can.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 13 '05 #24

P: n/a
Matt Kruse said the following on 10/12/2005 11:07 PM:
The FAQ is great, but it's too big, too long, and too bloated to
be scanned quickly in a lunch break by someone who wants to avoid typical
day-to-day JS problems.


Ditto. It's becoming an "FAQ Book", not an FAQ document. Maximized at
1280x1024, it is somewhere around 20 pages long. I am scared to see how
many pages long it is at 800x600 or so.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 13 '05 #25

P: n/a
Matt Kruse said the following on 10/12/2005 10:36 AM:
Randy Webb wrote:
[snip]

I've corrected a few of the things you've suggested. Thanks!


Sure thing. Maybe some day when I get around to creating a good test
page, you can test one of my day dream creations.
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.


They have advantages and disadvantages. The best you and I can do is
agree to disagree on them. To each his own, ya know?

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 13 '05 #26

P: n/a
Matt Kruse wrote:
Richard Cornford wrote:
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 makes sense that if you favor an approach to development,
that you would have something to offer which takes that
approach.


"Something to offer" is a bit of a loaded term.
Much the same way that you 'promote' closures and offer
documentation and example scripts using the approach.
I do not "offer" anything. I have written and published explanations of
closures and example of their application. I have also written
extensively on my approach to browser scripting, and published numerous
specific examples. If you have not seen them then that is probably
because you have not been looking.
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.


Few would argue in favor of 'monolithic' generalised
libraries.


Few here would, but they are argued in favour of.
Libs with a specific purpose and just a little extra
'code bloat' as some might call it is a different story
entirely.
What you characterise as a "little extra" code bloat is not necessarily
that little. Every time one of your libraries satisfies a demand for a
less common facility you increase the download for everyone who has no
use or interest in that facility. Every time you need to do something
you must do it in the most general way available, while many actual
applications may preclude much of what the general code must take into
account. Allowing simpler, faster, more specific code to be used in its
place, if that general approach was not lost in the depths of an
interdependent library file. And every time more than one library is
used the odds are good that entire chunks of more or less identical
functionality are being reproduced in each one.

So they are not entirely different stories. Your strategy is a reduction
of a significant problem that is present in monolithic generalised
libraries, but only a small reduction offering diminishing returns as
more of your libraries are used together.

A layered approach to code re-use where systems are built upon many low
level components providing small sets of facilities to all the higher
layers in the system allows the minimisation of redundant code in any
application, and allows the choosing of components that provide those
facilities in a way that closely matches the context in which they are
used, removing the overheads of being general in the face of the
specific. Thus providing the benefits of code re-use for efficient
software authoring but avoiding the bloat and overheads inherent in high
level self-contained general libraries.
You often confuse the two.
The two are not sufficiently different to justify the distinction in
many cases. If you propose that the reduction in code bloat achieved by
moving form monolithic generalised libraries to task specific libraries
is an important difference then the fact that the remaining inherent
code bloat can largely be removed by adopting a third strategy makes
drawing a distinction between the two less effective strategies
superfluous.
Here you are arguing for expedience, but "best practice"
most definitely is about ideals that should be aspired
to and not short term expedience.


The two goals are not mutually exclusive.


But short-term expedience is not a justification for a particular
practice as a "Best Practice".
A developer may need a short-term solution, yet be interested
in learning to do things the 'right' way long-term.
Or, more likely, recognise a best practice but see expedience as a
reason for not employing it in a specific context.
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?


Ridiculous statement.
I've used many 3rd-party Java libraries which I
certainly would not be able to develop on my own.


And Java is a language where the use of libraries is fundamental to the
language's design.
Yet I benefitted by being able to deliver more
advanced functionality in a shorter timeline.
And the relevance of Java authoring to browser scripting is?
You seem to argue in favor of writing everything of scratch,
You know that I don't.
which is absurd.
As it would be, if true.
You surely don't follow that reasoning yourself. You just
define it differently to suit your needs.
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 do not 'promote' my libraries.


Oh yes you do. Look at the domain names you have purchased and tell me
you are not in the business of promoting your scripts.
I offer them as solutions to specific cases in this group
where my already-developed solution matches exactly what
the poster needs.
If that was actually true your activities would not have attracted any
comment. You frequently propose the use of your scripts without any
indication that the OP is working in the restricted contexts in which
many of them are appropriate, or any indication that the OP is capable
of doing the extra work necessary to deploy them in a reliable way in
the default Internet context (and given the attitude towards "average
web developers" expressed below it appears that your assumption would be
that they were incapable of undertaking that extra work).
There is no financial motivation. There may be some
financial reward, but it is certainly not a motivating
factor.
Ira Baxter also maintains that it is not the financial return that
leaves her promoting her obfuscator in the face of the reasoned
arguments for its futility. It looks like behaviour that can only be
explained by a vested interest or mental illness.

Without a vested interest my expectation would be that individuals would
be interested in identifying the best possible approaches towards
achieving their goals. And willing to engage in, and be swayed by,
reasoned debate about the possible approaches, even to experiment with
the possibilities to better assess their relative merits. So
encountering persistent intransigence suggests questioning its
motivation.
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.


This is a valid thought, and I had considered adding a
"Why?" link which would open up a pre-hidden DIV explaining
in a little more detail the rationale behind the
recommendation.


That seems a needlessly complicated approach to presenting necessary
information, but let us know when it is done as it is the rational
behind a recommendation that is necessary in assessing its worth.
Your page makes no justifications for the items it proposes
as "best practice" and so is reduced to a sequence of personal
assertions.


As is any recommendation. Having a detailed justification
doesn't make it any more 'correct', and readers are still
open to disagree with the justification.


The point of providing a justification for any recommendation is
precisely so that the reader can disagree with the recommendation. Any
proposed "Best Practice" that has a flawed or hollow justification is
unlikely to actually be a "Best Practice". You need to know why
something is being proposed in order to see what it is that makes it a
"Best Practice". And is something really is a "Best Practice" there
should be a really good reason for that being the case.
Any 'truth' is only as good as your faith in
the person telling it to you.
Truth is based entirely on an appeal to authority? You cannot really
believe that?
But philosophy is not really on topic...
Epistemology is entirely relevant to the question of identifying "Best
Practice" form a set of proposed "Best Practices".
For example, you propose that people use bracket notation,
seemingly to the exclusion of dot notation (insane as that
would be).


For any developer who doesn't know enough to decide for
themselves to do differently,


A "developer who doesn't know enough to decide for themselves" which
type of property accessor to use in any given context? A vision of web
development as a bunch of headless chickens careering about in the dark
continuously bumping into each other and bouncing off walls. The pity is
that that does appear to describe the reality in some organisations, but
it does no good to be pandering to the notion that this would be an
acceptable situation.
I think it is the 'safest' recommendation.
So your are proposing that bracket notation should be used to the
exclusion of dot notation (and proposing it as a "best practice")? Such
a proposal is insane. Bracket notation is slower than dot notation
because of the additional requirement to evaluate the expression within
the brackets and type-convert the result to a string. It should be the
less used property accessor, with bracket notation being used where it
is necessary, and possibly where it contributes to source code clarity
(such as in differentiating between names originating in the HTML and
the javascript).
It will certainly lead to fewer problems and less
confusion for the average web developer.
Only if the "average web developer" really is a headless chicken. The
very worst web developers may well be that incapable of understanding
what they are doing, but for the majority the real solution to not
knowing enough to "decide for themselves" is to provide the explanation
that would facilitate informed decision making.
On the whole your page is too superficial to justify
its title


On the contrary, I've received great feedback so far from
many others who said they immediately benefitted from it.


Marvellous, you demonstrate utter contempt for the intellectual
potential of the "average web developer" and then cite their opinion as
in some way significant to an assessment of your page.
Javascript is a mystery to many. A short, concise, easy
to understand document such as thing can be very valuable
to those who may be experienced programmers but just want
a push in the right direction when it comes to javascript.
And a short concise easy to understand document can also do significant
harm, depending on its contents. Being short is not of itself a good
thing, when the result can be too superficial to promote understanding.
But then if you start form the presupposition that the average web
developer is incapable of achieving a technical understanding of what
they are doing omitting all technical explanation may seem more
justified than its inclusion.
The FAQ is great, but it's too big, too long, and too
bloated to be scanned quickly in a lunch break by
someone who wants to avoid typical day-to-day JS problems.
This group's FAQ is quite big, and all the pressure is to make it
bigger. It never was designed to be read in a lunch break. But then you
cannot learn javascript in a lunch break, or 24 hours, or a couple of
weeks, and expecting to be able to do so is totally unrealistic.
For one who criticizes so much, I would expect to see your
alternative 'Best Practices' document offered on the web
somewhere. It is conspicuously absent.


You see a superficial document as appropriate in addressing the question
of "Best Practice", I don't. Late last year I was involved in the
process of creating a javascript authoring standards document for the
software house for which I work. The intention was to lay down formal
rules and "Best Practices" to be followed by our sub-contractors in
creating javascript (but inevitably, once formalised, those same rules
would also have to be followed internally). The resulting document is 50
sides of A4 and does no more than lay down rules that will be followed.
The criteria for choosing those rules, the reasoning behind them, the
arguments about them and the decision making that resolved those
arguments are not part of that document. They were the subject of
discussion in various meetings and extensive e-mail conversations, and
then only when a specific "Best Practice" was subject to disagreement
(as most were adopted without opposition or debate).

I think that a document about "best Practices" should be about best
practices, rather than a list of practices that one individual believes
to be "best Practices". So such a document has to include the
explanations/justifications that allow the reader to understand why a
practice is being proposed, what benefits are expected to follow from
its adoption, and how its adoption is likely to impact upon other
aspects of the scripting task. And for me such a document should include
practices that are argued as best practices but with which I personally
disagree, along with their justifications. The result should be a
document that allowed reader to cherry-pick the set of "best practices"
that best suited their authoring context, and do so on the basis of
informed decision making.

The result is not a screen full of text, it is probably about the size
of a largish chapter in a book. So is it surprising that I have not
created such a document, given the amount of work involved?

That is a fundamental difference between us. I will not be satisfied to
publish anything less than a document that allows its readers to make
informed decisions about the adoption of best practices (and so also
make informed decisions about when it might be expedient to disregarded
them), and you see your best interests in pandering to a flock of
headless chickens.

Richard.
Oct 13 '05 #27

P: n/a
Richard Cornford wrote:
[snip]
Richard, your posts are too verbose to be responded to in detail, and we've
disagreed on this before. As I've said before, you're an intelligent guy and
you do good stuff, but your perspective is very different from mine. Your
experience with Javascript is not the norm. In my experience with many web
developers, Javascript is this piece-of-crap scripting language that they
have to deal with and struggle with. It gets in the way of what they want to
do, but they have to use it. Many have no interest in learning the language
or its quirks, nor do they want to spend hours learning best practices of
FAQs.

My approach is to cater to those people and others who have no interest in
becoming javascript experts. I realize and accept that they will not read
the FAQ or a book on the topic, nor will they experiment with browser quirks
or other js-related topics. The question is, if you're working with these
people, do you continue to let them make common easily-corrected mistakes,
or do you identify the "low hanging fruit" and help them fix the most common
problems quickly and easily, so you can at least get some immediate benefit?
Do you tell them to 'write their own' calendar popups and tree structures
because they need to know the inner-workings, only to see that their end
result is horrible and goes into production because of the deadline? Or do
you offer a generalized library that might have some 'bloat' but
accomplishes the task way better than they would have written themselves?

Not everyone wants to be a javascript expert. You do. That's nice. But don't
pigeon-hole everyone into your mindset.
What you characterise as a "little extra" code bloat is not
necessarily that little. Every time one of your libraries satisfies a
demand for a less common facility you increase the download for
everyone who has no use or interest in that facility.
The point is - who cares? If it's an extra 5k or even 10k, that is often way
over-shadowed by graphics sizes, flash, etc.
If your goal is to create tight, compact pages, then fine - don't use libs.
But that is _NOT_ a requirement for most people.
The convenience of using a lib with a little code bloat is more important
than the extra few k of text that is downloaded.
And
every time more than one library is used the odds are good that
entire chunks of more or less identical functionality are being
reproduced in each one.
Not if used correctly.
Yet I benefitted by being able to deliver more
advanced functionality in a shorter timeline.

And the relevance of Java authoring to browser scripting is?


Same concept, different language/environment.
Develop a solution to a general problem and package it up with an interface.
People can then use your solution to the problem in their work, even if your
solution contains much more functionality than they actually need.
Without a vested interest my expectation would be that individuals
would be interested in identifying the best possible approaches
towards achieving their goals. And willing to engage in, and be
swayed by, reasoned debate about the possible approaches, even to
experiment with the possibilities to better assess their relative
merits.
I'd say that I definitely fall into that categorization.
The point of providing a justification for any recommendation is
precisely so that the reader can disagree with the recommendation.
The target audience for my recommendations (which should be clear by the
content) are generally people who may not even have enough knowledge to
decide for themselves whether the justification is reasonable or not. Or
they may not even care. They just want their stuff to work.
A "developer who doesn't know enough to decide for themselves" which
type of property accessor to use in any given context? A vision of web
development as a bunch of headless chickens careering about in the
dark continuously bumping into each other and bouncing off walls. The
pity is that that does appear to describe the reality in some
organisations, but it does no good to be pandering to the notion that
this would be an acceptable situation.
It describes the reality in _many_ organizations, and _many_ individuals.
You don't see regularly how many people _DESPISE_ javascript?
I see absolutely horrible javascript practices so often that even suggesting
the most basic of 'best practices' would add value to many people. And that
is my goal.
On the contrary, I've received great feedback so far from
many others who said they immediately benefitted from it.

Marvellous, you demonstrate utter contempt for the intellectual
potential of the "average web developer" and then cite their opinion
as in some way significant to an assessment of your page.


No, my point is, there are many who have a very basic understanding of
javascript, and a document like this is short, practical, and adds immediate
value to their development.
But then
you cannot learn javascript in a lunch break, or 24 hours, or a
couple of weeks, and expecting to be able to do so is totally
unrealistic.
And yet your expectation is that every web developer in the world should
devote this much time to learning it and using it correctly.
That expectation is highly absurd.
My point is, people don't have to invest that much time to do many of the
tasks which they want to accomplish. If all they want is a date picker on
their page, they can have one in 10 minutes. They don't need to spend weeks
learning Javascript to implement one. Yet your 'elitist' approach would say
they are not worthy of one if they aren't willing to invest the time. That's
completely unrealistic.
Late last year I was involved
in the process of creating a javascript authoring standards document
for the software house for which I work.
...
The resulting document is 50 sides of A4 and does no
more than lay down rules that will be followed.
Such a document would be completely worthless to most web developers.
The result is not a screen full of text, it is probably about the size
of a largish chapter in a book. So is it surprising that I have not
created such a document, given the amount of work involved?
There is value in partially solving a problem.
If you can add value in a specific area, even without solving the entire
problem, that is a good thing.
A 'Best Practices' document doesn't need to cover everything. IMO.
That is a fundamental difference between us. I will not be satisfied
to publish anything less than a document that allows its readers to
make informed decisions about the adoption of best practices (and so
also make informed decisions about when it might be expedient to
disregarded them), and you see your best interests in pandering to a
flock of headless chickens.


I'm realistic. You're idealistic.
I'm practical. You're a perfectionist.
I cater to the masses. You cater to those you deem worthy.
I understand the problems of the average developer. You tell them to RTFM.

I prefer my view.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Oct 13 '05 #28

P: n/a
JRS: In article <di*******************@news.demon.co.uk>, dated Thu, 13
Oct 2005 00:52:31, seen in news:comp.lang.javascript, Richard Cornford
<Ri*****@litotes.demon.co.uk> posted :
Matt Kruse wrote:

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.

One should, however, distinguish in debate between at least two distinct
forms of bloat javascript bloat.

(0) Writing multiply-repeated code, for example to add a leading zero or
to check that a field is non-empty, when it would be perfectly simple to
write a function (or method) to be called multiple times.

(1) Putting a large number of perhaps well-written functions in a single
include file, so that all readers of any page that uses any of the
functions must fetch the whole lot.

(2) Writing and using a single large function to do many varieties of
one thing, perhaps controlled by parameters, when only one variety will
be used at any given time, but the whole must be loaded. Example, a
function to read and validate a date in various field orders, possibly
with suffices, possibly with months in letters, in various languages,
possibly with roman numerals. Writing it as an exercise is harmless;
deployment in full is generally wasteful.
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.


You think that, Richard : but then you're not a Merkin. Perhaps the
document should be called "Javascript for dummies", though IIRC that
title has already been taken.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Oct 13 '05 #29

P: n/a
JRS: In article <3r************@uni-berlin.de>, dated Wed, 12 Oct 2005
19:30:42, seen in news:comp.lang.javascript, Gérard Talbot
<ne***********@gtalbot.org> posted :
Matt K. explicitly states that numeric indices is a bad practice.
"Referencing forms using indexes, such as document.forms[0] is bad
practice."
If he wrote only that about it, he's wrong, through not giving the
possibilities adequate consideration.

Using fixed numeric indices to refer to what could be a named form is
indeed bad, since the page might get edited into another order. If a
page clearly will only ever have a single form, the practice is
harmless.

If one must iterate through all forms, then sing varying numeric indices
is reasonable, perhaps inevitable.

And if for some unaccountable reason one were to need to refer, say, to
the form which comes third, even after possible rearrangement, then a
fixed index would be appropriate.
[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.
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.


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.


Then you are wrong; and sentences should start with a capital letter.
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?


Yes, but the book does date from before the matter was (possibly first)
raised here.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Oct 13 '05 #30

P: n/a
JRS: In article <N9********************@comcast.com>, dated Wed, 12 Oct
2005 23:33:07, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :
Dr John Stockton said the following on 10/12/2005 4:59 PM:
JRS: In article <28********************@comcast.com>, dated Tue, 11 Oct
2005 23:15:34, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :
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.


Then why is it that with this code:

var s="10";
var t="12";
var total = Number(s) + Number(t);
alert(total);

That you are one of the first ones to point out:

"Don't convert Strings to Numbers that way, use the unary + because its
*faster*"

The apparently quoted sentence is making a general statement about
string-to-number conversion, prompted (you say) by the code above; it
makes no claim that the particular example would execute perceptibly
faster.

For string-to-number, unary + has several advantages. It's faster to
type and faster to download, being briefer. It never treats a pure
decimal digit string as other than decimal; no concern about forgetting
the parameter 10.

And it's possible to use it in a loop that takes longer than user
reaction time, so that a gain in speed is not useless.
Either its speed or its "good enough". Whats the standard?
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.
And if you writing an entire holidays table then you are writing HTML
and not text so your comparison is irrelevant.


Writing and executing HTML will take at least as long as writing and
displaying a similar amount of plain text. Therefore if HTML is not too
slow, plain text will not be.

So I tested with plain text; DynWrite took under 100 ms to write 15000
characters (in eval(), too). That's well over a screenful. So my point
is mow better demonstrated.
But that aside, the standard I have for myself is not to be "good
enough", it's to be the best that I can.


Then why are your criticisms nowadays always so ill-judged? ... must be
the best that you can do.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Oct 13 '05 #31

P: n/a
Dr John Stockton said the following on 10/13/2005 5:29 PM:
JRS: In article <N9********************@comcast.com>, dated Wed, 12 Oct
2005 23:33:07, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :
Dr John Stockton said the following on 10/12/2005 4:59 PM:

JRS: In article <28********************@comcast.com>, dated Tue, 11 Oct
2005 23:15:34, seen in news:comp.lang.javascript, Randy Webb
<Hi************@aol.com> posted :
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.
Then why is it that with this code:

var s="10";
var t="12";
var total = Number(s) + Number(t);
alert(total);

That you are one of the first ones to point out:

"Don't convert Strings to Numbers that way, use the unary + because its
*faster*"


The apparently quoted sentence is making a general statement about
string-to-number conversion, prompted (you say) by the code above; it
makes no claim that the particular example would execute perceptibly
faster.


Oh geez John, you get worse and worse everyday. Let me find you another
quote that I recall:

<quote>
Once upon a time, you made only intelligent remarks.
</quote>

You are beginning to fit that bill. You can't seem to make up your mind
what practices you want to suggest/follow. It seems to depend on the day
of the week.

Your perception that "innerHTML is good enough" is just plain ignorant
at best.
For string-to-number, unary + has several advantages.
And several disadvantages.

It's faster to type and faster to download, being briefer.
If you type so slow that typing Number takes you that much longer than
typing +, then you don't need to be writing code, you need to be taking
typing lessons.

And, are you really serious about the "faster to download" when it comes
to 5 characters of data?
It never treats a pure decimal digit string as other than decimal;
no concern about forgetting the parameter 10.

I wrote nothing about the parameter 10 which Number does not need. I
used Number for that very specific reason instead of parseInt and
parseFloat.

But, are you saying that Number(k) will treat a pure decimal digit
string as anything other than decimal?
And it's possible to use it in a loop that takes longer than user
reaction time, so that a gain in speed is not useless.
So now you use it for speed but use the slower innerHTML because its
"good enough"?
Main Entry: hyp·o·crite
Pronunciation: 'hi-p&-"krit
Function: noun
Etymology: Middle English ypocrite, from Old French, from Late Latin
hypocrita, from Greek hypokrites actor, hypocrite, from hypokrinesthai
: a person who puts on a false appearance of virtue or religion
- hypocrite adjective
Either its speed or its "good enough". Whats the standard?

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.
And if you writing an entire holidays table then you are writing HTML
and not text so your comparison is irrelevant.

Writing and executing HTML will take at least as long as writing and
displaying a similar amount of plain text. Therefore if HTML is not too
slow, plain text will not be.


The time it takes will be directly proportional to the amount of HTML
that is in the string.
So I tested with plain text; DynWrite took under 100 ms to write 15000
characters (in eval(), too). That's well over a screenful. So my point
is mow better demonstrated.
No, writing plain text using innerHTML will NOT show its speed problems.
Perhaps you should test the DOM2 methods to inject plain text into a
wrapper element. But does your antiquated IE4 support it?
But that aside, the standard I have for myself is not to be "good
enough", it's to be the best that I can.

Then why are your criticisms nowadays always so ill-judged? ... must be
the best that you can do.


It probably would be the "best that I can do" if I aspired to be only as
good as you. I have higher goals/standards/expectations than that for
myself - you should consider doing the same. It would help you tremendously.

Now, you can babble all you want. I have better things to do than argue
with you about your ignorance of what you are writing about. Stick to
numbers and dates, they are your strong point. dHTML and the speed of it
is not.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq
Oct 14 '05 #32

P: n/a
In article <TF**************@merlyn.demon.co.uk>, Dr John Stockton
<jr*@merlyn.demon.co.uk> writes
JRS: In article <3r************@uni-berlin.de>, dated Wed, 12 Oct 2005
19:30:42, seen in news:comp.lang.javascript, Gérard Talbot
<ne***********@gtalbot.org> posted :


<snip>
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.


Then you are wrong; and sentences should start with a capital letter.

<snip>

Not funny. This newsgroup is read by beginners; we mustn't trick them
into writing ParseInt (with a capital P).

DB is an abbreviation for database.
dB is a ratio.

dBaseII is (was?) a trade mark.
DBaseII is not, or is a different trade mark.

mW powers your torch.
MW melts scrap metal.

John
--
John Harris
Oct 14 '05 #33

P: n/a
Randy Webb a écrit :
Gérard Talbot said the following on 10/12/2005 7:52 PM:
Matt Kruse a écrit :


<snip>
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.

And is totally useless with JS disabled.......


<body onload="document.getElementById('idParg').style.di splay =
'block';" (...)>
(...)
<p id="idParg" style="display: none;"><button type="button"
onclick="doSomething();">Some caption describing action</button></p>

If JS is enabled, then the button will be visible and usable. If JS is
disabled, the button won't be visible nor usable.

You may even use (toggle) alternate content depending on JS support
depending on what exactly the JS action is supposed to do, should do.
There are many possibities depending on the page goals.
I still insist that a link should be a link, should behave like a link,
should look like a link, etc... Otherwise, it's misusing markup code,
semantic markup code.

Gérard
--
remove blah to email me
Oct 14 '05 #34

P: n/a
Matt Kruse a écrit :
Gérard Talbot wrote:
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.

I've updated a few places pointed out to be more 'correct', fwiw.

Well, then we disagree. I use href="#" all the time within web apps
that require javascript.


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.

So?

1) Using things for their intended purpose leads to less innovation.


This is over-exaggerated. This is confusing issues.

The web wouldn't be where it is at now if people only used things for their
'intended purpose'.

Using tables for page layout is not innovation.
Using dozens of <br> instead of CSS margin-top or margin-bottom is not
innovation.
Using dozens of &nbsp; instead of CSS padding or CSS text-indent is not
innovation.
Using empty <p></p> instead of CSS margin-bottom is not innovation.
Using <blockquote> to indent a section when such text section has
nothing to do with a quote is not innovation. etc..

There are billions of webpages which do just that which make their
webpages bloated, a nightmare tag soup mess impossible to update, slow
to download, etc..
2) Links are often preferred for triggering javascript functionality because
of design issues. For example, a DIV showing a list of matches to a
partially-filled input box may be <a> links which trigger a function to
populate the box. Having them as buttons would be ridiculous. And sometimes,
links just look and behave better.


If the <a> links brings up a new page content into a window, then it
would be adequate usage. I don't know for sure in the example you give
since I do not see, can not examine the example you are referring to.

What I am against is improper use of markup which will inevitably affect
the way conformant user agents will address such markup. It's about
software interoperability.
E.g.: A form submission should be using a button that looks/is/behaves
like a submit button, not a link (<a>). Search engines do not index
submit buttons but they will index links semantically used as links. A
lot of assistive technologies (speech browsers, translation features,
etc.) will try to render as best they can what is semantically coded as
links to begin with.

Regards,

Gérard
--
remove blah to email me
Oct 14 '05 #35

P: n/a
Matt Kruse a écrit :
I've updated a few places pointed out to be more 'correct', fwiw.


This is one of your change:

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

If the document is HTML 4.01 strict, it will still trigger a validation
error while

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

will not trigger a validation error.

Gérard
--
remove blah to email me
Oct 14 '05 #36

P: n/a
On 14/10/2005 21:13, Gérard Talbot wrote:

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

will not trigger a validation error.


True, but since when have INPUT elements been part of a paragraph? A DIV
or FIELDSET element is more appropriate.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Oct 14 '05 #37

P: n/a
Gérard Talbot wrote:
<form name="myform" action="[url]">
<p><input type="text" name="val1" value="1">
<input type="text" name="val2" value="2"></p>
</form>
will not trigger a validation error.


I don't see that as a compelling reason to change it.

Validation is a tool, not a goal in itself.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Oct 14 '05 #38

P: n/a
Gérard Talbot wrote:
The web
wouldn't be where it is at now if people only used things for their
'intended purpose'.

Using tables for page layout is not innovation.


Oh yeah? Were you around to remember when the <table> tag was introduced by
Netscape? It made page layout *possible*. Although it may not have been its
inteded purpose, it certainly was a huge step in moving the web towards more
where it is today.

Had everyone stuck to the rules that purists have about when to use tables,
the web would have been much uglier for much longer.

I still use tables for layout. Why? Because it works consistently across
browsers, it's much easier to accomplish nice layouts that equivalent CSS
layout, it degrades more consistently than CSS, and it's easier. I don't
care if it's "semantically" wrong. It works. Better than the alternatives in
most cases.

There are many factors that must be taken into consideration when deciding
which approaches to use for the web. Validation is just one of those
factors, and for me it's very low on the list. People who put it at the top
are usually missing the point, IMO.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Oct 14 '05 #39

P: n/a
Gérard Talbot said the following on 10/14/2005 3:35 PM:
Randy Webb a écrit :
Gérard Talbot said the following on 10/12/2005 7:52 PM:
Matt Kruse a écrit :

<snip>
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.


And is totally useless with JS disabled.......


<body onload="document.getElementById('idParg').style.di splay =
'block';" (...)>
(...)
<p id="idParg" style="display: none;"><button type="button"
onclick="doSomething();">Some caption describing action</button></p>


If you want a button that is JS dependent, then have JS generate that
button :)

JS generating the button also doesn't require as much feature detection
as the above onload /should/ do but doesn't.
If JS is enabled, then the button will be visible and usable. If JS is
disabled, the button won't be visible nor usable.


If the page error's any time before the onload fires, then the user
doesn't get the button even though scripting is enabled. That same
problem arises with the JS generated button though.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 14 '05 #40

P: n/a
John G Harris said the following on 10/14/2005 2:41 PM:
In article <TF**************@merlyn.demon.co.uk>, Dr John Stockton
<jr*@merlyn.demon.co.uk> writes
JRS: In article <3r************@uni-berlin.de>, dated Wed, 12 Oct 2005
19:30:42, seen in news:comp.lang.javascript, Gérard Talbot
<ne***********@gtalbot.org> posted :

<snip>
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.


Then you are wrong; and sentences should start with a capital letter.


<snip>

Not funny. This newsgroup is read by beginners; we mustn't trick them
into writing ParseInt (with a capital P).


And if you had written ParseInt then he would have undoubtedly noted
that it should be parseInt :-)
DB is an abbreviation for database.
dB is a ratio.

dBaseII is (was?) a trade mark.
DBaseII is not, or is a different trade mark.

mW powers your torch.
MW melts scrap metal.


Don't fret the good doc John, he isn't worth it :)

Although I personally think a "better practice" for converting a String
to a Number is by Number(string).

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 14 '05 #41

P: n/a
Randy Webb a écrit :
Gérard Talbot said the following on 10/14/2005 3:35 PM:
Randy Webb a écrit :
Gérard Talbot said the following on 10/12/2005 7:52 PM:

Matt Kruse a écrit :
<snip>

> 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.


And is totally useless with JS disabled.......

<body onload="document.getElementById('idParg').style.di splay =
'block';" (...)>
(...)
<p id="idParg" style="display: none;"><button type="button"
onclick="doSomething();">Some caption describing action</button></p>

If you want a button that is JS dependent, then have JS generate that
button :)


That is also a possibility. I personally hate using document.write(),
even with a defer attribute ... but that's another ball game/discussion.
JS generating the button also doesn't require as much feature detection
as the above onload /should/ do but doesn't.

Your comment is interesting because it meets another point that I tried
to make in this thread. If your goal is to support modern browsers (1),
then why do you need to detect the support for getElementById ? I said
in my first post in this thread that MSIE 5.x support getElementById.
You gave examples and a how-to to support MSIE 4.x in your 1st draft of
your document and I still see that in your fallback recommendation for
that unique particular browser version. I disagree with such
recommendation. IMO, if an user visits a webpage that has/uses DHTML
with MSIE 4, then he should be told to upgrade, period. Your document
still keeps the door open to MSIE 4.

If I (or anyone) do not see a single reason as to resort to
document.all, document.all[] and document.all(), then I (or anyone)
should not see a single reason to verify the support for
document.getElementById() either.
If JS is enabled, then the button will be visible and usable. If JS is
disabled, the button won't be visible nor usable.

If the page error's any time before the onload fires, then the user
doesn't get the button even though scripting is enabled.
We're already talking about an exception here. I have assumed that the
page is correctly and properly coded (markup code, CSS code, JS code) to
begin with and that the page context is under normal conditions... Of
course, if there is a tsunami happening or if the user unplugs his
computer as the document is loading, then the script won't achieve its
goals.

That same problem arises with the JS generated button though.


I replied a code to the situation where JS was disabled. Basically the
same code could have been provided for a badly semantically coded <a>
link (instead of a <button>).

In this thread, I believe I've tried to bring up chunks of code,
references, more complete examples trying to substantiate my claims.

(1) Some refer to browsers/browser versions released after 2001. Some
others refer to 5th generation browsers. Some others to browsers being
js-capable of modifying its DOM tree. In all cases, MSIE 4 does not meet
any of the above conditions.

Gérard
--
remove blah to email me
Oct 15 '05 #42

P: n/a
Matt Kruse a écrit :
Gérard Talbot wrote:
The web
wouldn't be where it is at now if people only used things for their
'intended purpose'.
Using tables for page layout is not innovation.

Oh yeah? Were you around to remember when the <table> tag was introduced by
Netscape? It made page layout *possible*. Although it may not have been its
inteded purpose, it certainly was a huge step in moving the web towards more
where it is today.


Same thing with the invention of wheels and fire. That was then. Now is
much different. We live now in houses, work in buildings, etc.. which
are constructed, built according to standards, norms, checkings, laws,
etc... Don't get me wrong: I will always agree with you that the
invention of wheels and fire were major innovations.

Had everyone stuck to the rules that purists have about when to use tables,
the web would have been much uglier for much longer.

That's your opinion.
I still use tables for layout. Why? Because it works consistently across
browsers,
People are using more and more mobile devices for which tables and
nested tables used for layout cause accessibility problems. Less and
less people are using old browsers (MSIE 4, NS 4, etc.).

it's much easier to accomplish nice layouts that equivalent CSS layout, it degrades more consistently than CSS, and it's easier.

People are moving toward more CSS compliant browsers, not the opposite.
And there are now several dozens of freely available CSS templates which
can replace table design.
I don't care if it's "semantically" wrong. It works. Better than the alternatives in
most cases.
We're a bit off topic here (you chose to address one single sentence of
my post - table design vs CSS).

I assure you that a "Javascript Best Practices" document should try to
be a model of quality in its content, in its example, in its design.
There is enough javascript copy-N-paste sites around promoting pretty
much anything/everything with overall typical "Krusty burger" quality.
There are many factors that must be taken into consideration when deciding
which approaches to use for the web. Validation is just one of those
factors, and for me it's very low on the list.
Then you should clearly indicate this into your document. You should
explicitly indicate that your Javascript Best Practices document refers
to HTML pages, not XHTML pages. You should explicitly indicate in your
Javascript Best Practices that semantic and validation are very low
priorities, are not important issues, validation is just a tool,
whatever... It's your document: you should feel confortable with doing this.

People who put it at the top are usually missing the point, IMO.


I don't have Safari 1.x, Safari 2.x, Icab 3.x, etc.. installed on my
computer. Now, since I can not test my webpages with these browsers (and
a lot of other browsers and compliant user agents) and since I want to
support browsers and applications which are web standards compliant,
then my best shot is to write valid webpages in strict DTD. So, I
consider validation to be a 1st priority (not the sole one) when
finalizing the code of my webpages.

Gérard
--
remove blah to email me
Oct 15 '05 #43

P: n/a
Gérard Talbot a écrit :
Randy Webb a écrit :

You
I'm sorry Randy. Somehow, I thought I was replying to Matt K.
gave examples and a how-to to support MSIE 4.x in your 1st draft of
your document and I still see that in your fallback recommendation for
that unique particular browser version. I disagree with such
recommendation. IMO, if an user visits a webpage that has/uses DHTML
with MSIE 4, then he should be told to upgrade, period. Your document
still keeps the door open to MSIE 4.


Gérard
--
remove blah to email me
Oct 15 '05 #44

P: n/a
Gérard Talbot said the following on 10/14/2005 10:15 PM:
Randy Webb a écrit :
Gérard Talbot said the following on 10/14/2005 3:35 PM:
Randy Webb a écrit :

Gérard Talbot said the following on 10/12/2005 7:52 PM:

> Matt Kruse a écrit :
>

<snip>

>> 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.
And is totally useless with JS disabled.......
<body onload="document.getElementById('idParg').style.di splay =
'block';" (...)>
(...)
<p id="idParg" style="display: none;"><button type="button"
onclick="doSomething();">Some caption describing action</button></p>
If you want a button that is JS dependent, then have JS generate that
button :)


That is also a possibility. I personally hate using document.write(),
even with a defer attribute ... but that's another ball game/discussion.


True. Very true. But document.write is not the only way to dynamically
generate a button. Use the onload to trigger a function that will create
and append the button or insert it into a container.
JS generating the button also doesn't require as much feature
detection as the above onload /should/ do but doesn't.


Your comment is interesting because it meets another point that I tried
to make in this thread. If your goal is to support modern browsers (1),
then why do you need to detect the support for getElementById ? I said
in my first post in this thread that MSIE 5.x support getElementById.
You gave examples and a how-to to support MSIE 4.x in your 1st draft of
your document and I still see that in your fallback recommendation for
that unique particular browser version. I disagree with such
recommendation. IMO, if an user visits a webpage that has/uses DHTML
with MSIE 4, then he should be told to upgrade, period. Your document
still keeps the door open to MSIE 4.

If I (or anyone) do not see a single reason as to resort to
document.all, document.all[] and document.all(), then I (or anyone)
should not see a single reason to verify the support for
document.getElementById() either.


I think you have me mistaken for Matt. He wrote the document in
discussion, not me.

If you look at this entire thread, in a tree display, at my first reply
you will see that I also pointed out that IE5.0 supported gEBI.

If you go back through the c.l.j archives and search for the
document.all snippet that is in the clj FAQ then you will find that I
(Randy, not Matt) am the one that originally proposed it to be added to
the FAQ itself.

But the document.all versus document.getElementByID wasn't the subject
of my comment about feature/object detection. It was the assumption of
the style and display properties.
<snip>
That same problem arises with the JS generated button though.

I replied a code to the situation where JS was disabled. Basically the
same code could have been provided for a badly semantically coded <a>
link (instead of a <button>).


That depends on how the <a> is coded.

<a href="somePage.html" onclick="return someFunction()">Some Page</a>

If the function someFunction() either displays the contents of
somePage.html in the current window, opens a new window, or toggles
display on a div tag that contains the data in somePage.html then if JS
is disabled the end user still gets the same content, but via a
different mechanism.

And when an a tag is used to invoke a function, and it is coded
correctly, then it degrades gracefully in the absence of JS.

How is that bad coding?
In this thread, I believe I've tried to bring up chunks of code,
references, more complete examples trying to substantiate my claims.
And I have presented my thoughts and nothing more.
(1) Some refer to browsers/browser versions released after 2001. Some
others refer to 5th generation browsers. Some others to browsers being
js-capable of modifying its DOM tree. In all cases, MSIE 4 does not meet
any of the above conditions.


If a "modern browser" is a "5th Generation Browser" then where does that
leave Firefox 1.0.xx?

"5th Generation Browser" is as ambiguous a term as "modern browser".

My goal is to support as many browsers as I can (modern or not) that do
not require a lot of extra effort. And including a snippet of code that
allows a lot of JS to be execute in IE4 without a document.all branch in
every place I want to do something, then I do it. Even if it is just 1%,
the cost of doing it is neglible. With proper server-side scripting, it
is a simple matter of an include statement in a template document and
then the work to accomodate IE4 is zero.

The problem I have with IE4 support now is not with document.all itself.
When I gave the URL to the emulation that is in the FAQ it was not as
outdated as it is now. To /properly/ support IE4 now with the gEBI
emulation, you would have to prototype everything that a gEBI browser
supports that IE4 doesn't. It is *that* requirement that makes IE4 not
worth supporting.

My definition of "modern browser" though is one of "the last version of
each vendors browser".
--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 15 '05 #45

P: n/a
Gérard Talbot said the following on 10/14/2005 11:10 PM:
Gérard Talbot a écrit :
Randy Webb a écrit :
You

I'm sorry Randy. Somehow, I thought I was replying to Matt K.


No problem.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Oct 15 '05 #46

P: n/a
On 14/10/2005 22:00, Matt Kruse wrote:

[snip]
[Using TABLE elements for layout] certainly was a huge step in moving
the web towards more where it is today.


That's debatable. The idea of style sheets occurred quite early on, but
early proposals didn't concentrate on layout. It would actually appear
that layout tables moved the Web away from the direction that is being
taken today.

I doubt that anyone could truly predict what would have happened if both
style sheets had become layout-oriented and tables were semantic from
the outset. The Web may never had had to endure the abominations that
were published, and still are (to an extent).

Anyway, this is a topic for another group.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Oct 15 '05 #47

P: n/a
On 15/10/2005 03:15, Gérard Talbot wrote:

[snip]
I personally hate using document.write(), even with a defer attribute
[...]
If you're using the write method, then should never use the defer attribute.

[snip]
If your goal is to support modern browsers [...], then why do you
need to detect the support for getElementById ?
Because not directly supporting browsers doesn't mean generating errors
in them, especially when those errors can be avoided. Doing otherwise
makes the author look amateurish - that they didn't know what they were
doing.

[snip]
IMO, if an user visits a webpage that has/uses DHTML with MSIE 4,
then he should be told to upgrade, period.
Telling a user to upgrade is hardly a reasonable thing for a Web
developer to be doing. That's similar to thinking that one can tell a
user to enable client-side scripting; the user must be backwards if they
don't.

[snip]
If I (or anyone) do not see a single reason as to resort to
document.all [...]


I already gave one, and it had nothing to do with IE4.

[snip]
If the page error's any time before the onload fires, then the user
doesn't get the button even though scripting is enabled.


We're already talking about an exception here. I have assumed that
the page is correctly and properly coded (markup code, CSS code, JS
code) [...]


"Proper coding" doesn't stop a browser from erroring out if one tries to
use a method or object that doesn't exist unless feature detection is
considered to be part of "proper coding".

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Oct 15 '05 #48

P: n/a
JRS: In article <Sz**************@jgharris.demon.co.uk>, dated Fri, 14
Oct 2005 19:41:23, seen in news:comp.lang.javascript, John G Harris
<jo**@nospam.demon.co.uk> posted :
In article <TF**************@merlyn.demon.co.uk>, Dr John Stockton
<jr*@merlyn.demon.co.uk> writes
JRS: In article <3r************@uni-berlin.de>, dated Wed, 12 Oct 2005
19:30:42, seen in news:comp.lang.javascript, Gérard Talbot
<ne***********@gtalbot.org> posted :
<snip>
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.


Then you are wrong; and sentences should start with a capital letter.

<snip>

Not funny. This newsgroup is read by beginners; we mustn't trick them
into writing ParseInt (with a capital P).


Agreed. The solution is to recast the sentence so that parseInt does
not come first. Putting "Function " before it is generally
satisfactory.

mW powers your torch.
MW melts scrap metal.


Neither makes a good start for a sentence.

--
© John Stockton, Surrey, UK. ??*@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Check boilerplate spelling -- error is a public sign of incompetence.
Never fully trust an article from a poster who gives no full real name.
Oct 15 '05 #49

P: n/a
Michael Winter a écrit :
On 15/10/2005 03:15, Gérard Talbot wrote:
If your goal is to support modern browsers [...], then why do you
need to detect the support for getElementById ?


Because not directly supporting browsers doesn't mean generating errors
in them, especially when those errors can be avoided. Doing otherwise
makes the author look amateurish - that they didn't know what they were
doing.


I think you don't understand what I mean. Anyway, I'm tired of repeating
myself, explaining myself and providing examples, etc.
IMO, if an user visits a webpage that has/uses DHTML with MSIE 4,
then he should be told to upgrade, period.

Telling a user to upgrade is hardly a reasonable thing for a Web
developer to be doing. That's similar to thinking that one can tell a
user to enable client-side scripting; the user must be backwards if they
don't.

[snip]


Well, I def. disagree. I know I'm not the only one thinking that IE 4
and NS 4 users should be invited to upgrade.
webstandards.org Browser upgrade campain some years ago
browserhappy campain
alternate browser campain
modern browser campain
2 years ago, Netscape DevEdge had
http://devedge-temp.mozilla.org/upgrade.html
not to mention microsoft itself which dropped support for IE 4 many
years ago.
Even my own ISP told me they invite their users to upgrade and help IE 4
and NS 4 users to upgrade to recent browser versions.
Comparing enabling client-side script with conforting and encouraging
tacitly to continue to use IE4 is a big stretch and a very debatable
comparison.
If I (or anyone) do not see a single reason as to resort to
document.all [...]

I already gave one, and it had nothing to do with IE4.

[snip]


I've never had to use getElementsByTagName() myself before or ... maybe
once I did. I certainly never used getElementsByTagName("*").
There are also and already many other DOM 1 methods returning a
collection of nodes or a named list.
document.links
document.anchors
document.images
document.forms
objTable.rows
objTableRow.cells
objSelect.options
elements
etc.

document.all is mostly used in webpages (and seen in webpages as) to
access single nodes.
So I still do not see a single reason to resort to document.all.
But Matt K.'s document provides explanations on how to maintain its
usage, specifically for IE 4 users.
"
# Only fall back to using document.all as a last resort
# Only use it if you need to support IE versions earlier than 5.0
"

Gérard
--
remove blah to email me
Oct 15 '05 #50

136 Replies

This discussion thread is closed

Replies have been disabled for this discussion.