Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Little Help with JavaScript

3 views
Skip to first unread message

vaib

unread,
Oct 16, 2009, 1:58:40 PM10/16/09
to
Hi All,

I am relatively new to JavaScript and I have to develop something that
seems like a good amount o learning curve for me right now.

To make it simple here's the most simplistic view of what I have to do
- A page where two DIVs are placed side by side and there's a button
below. On the click of the button the DIVs should exchange their
positions ( ofcourse, with everything in them also being exchanged ).
I have to make it resolution free.

I do not need any code as such ( although any help is appreciated )
but what approach to take would be a great help.

Meanwhile I am also searching google ;)

Thanking in anticipation.


- Vaibhav

Luuk

unread,
Oct 16, 2009, 3:23:45 PM10/16/09
to
vaib schreef:

- start coding
- get help from Google
- for reference you might go to http://w3schools.com/js/default.asp
- when you have coded something, and get weird errors, post what you
have made, and ask questions...

--
Luuk

SAM

unread,
Oct 16, 2009, 5:48:58 PM10/16/09
to
Le 10/16/09 7:58 PM, vaib a �crit :

> Hi All,
>
> I am relatively new to JavaScript and I have to develop something that
> seems like a good amount o learning curve for me right now.
>
> To make it simple here's the most simplistic view of what I have to do
> - A page where two DIVs are placed side by side and there's a button
> below. On the click of the button the DIVs should exchange their
> positions ( ofcourse, with everything in them also being exchanged ).
> I have to make it resolution free.

Where are the divs ? (in another div, in the body?)

Suppose they are only 2 and in the body :


CSS:
====
div { width: 38%; margin: 5%; float: left; border: 1px solid }
#brk { text-align: center }

JS :
====
function move() { // move the 1st div at the end
var d = document.getElementsByTagName('DIV')[0];
document.body.appendChild(d);
}

html:
=====
<body>
<p class="brk"><button onclick="move()">xchange divs</button></p>
<div style="background:#ff5">
<h2>Div #1</h2>
<p>nothing to say</p>
</div>
<div style="color:red">
<h2>Div #2</h2>
<p>nothing more to say</p>
</div>
</body>

> I do not need any code as such ( although any help is appreciated )
> but what approach to take would be a great help.

The function appendChild moves the child to the end of concerned element
(from temp (document.createElement) or from the DOM already displayed)

If you want to move to a certain place use insertBefore
(in the same way as given above)


> Meanwhile I am also searching google ;)

<https://developer.mozilla.org/En/DOM/Node.appendChild>
and see also :
insertBefore, replaceChild, removeChild and cloneNode

--
sm

Dr J R Stockton

unread,
Oct 16, 2009, 6:33:44 PM10/16/09
to
In comp.lang.javascript message <5bf6ef14-70ae-4ec9-aeed-123e5a6fbdb0@z3
g2000prd.googlegroups.com>, Fri, 16 Oct 2009 10:58:40, vaib
<vaibhav...@gmail.com> posted:

>To make it simple here's the most simplistic view of what I have to do
>- A page where two DIVs are placed side by side and there's a button
>below. On the click of the button the DIVs should exchange their
>positions ( ofcourse, with everything in them also being exchanged ).
>I have to make it resolution free.

Consider

<div ID=A style="width:50%; background:lime; float:left">AAA</div>
<div ID=B style="width:50%; background:aqua; float:right">BBB</div>
<input type=button onClick="Swap()">

<script>
function Swap() { var AA, BB, T
AA = document.getElementById("A")
BB = document.getElementById("B")
T = AA.style.cssFloat
AA.style.cssFloat = BB.style.cssFloat
BB.style.cssFloat = T }
</script>

--
(c) John Stockton, nr London UK. ?@merlyn.demon.co.uk IE7 FF3 Op9 Sf3
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<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.

Jorge

unread,
Oct 16, 2009, 7:53:38 PM10/16/09
to
On Oct 17, 12:33 am, Dr J R Stockton <reply0...@merlyn.demon.co.uk>
wrote:
> (...)

>         <script>
>         function Swap() { var AA, BB, T
>           AA = document.getElementById("A")
>           BB = document.getElementById("B")
>           T = AA.style.cssFloat
>           AA.style.cssFloat = BB.style.cssFloat
>           BB.style.cssFloat = T }
>         </script>

Not even a single semicolon ?

--
Jorge.

vaib

unread,
Oct 17, 2009, 5:34:55 AM10/17/09
to
On Oct 17, 12:23 am, Luuk <l...@invalid.lan> wrote:
> vaib schreef:
>
>
>
>
>
> > Hi All,
>
> > I am relatively new to JavaScript and I have to develop something that
> > seems like a good amount o learning curve for me right now.
>
> > To make it simple here's the most simplistic view of what I have to do
> > - A page where two DIVs are placed side by side and there's a button
> > below. On the click of the button the DIVs should exchange their
> > positions ( ofcourse, with everything in them also being exchanged ).
> > I have to make it resolution free.
>
> > I do not need any code as such ( although any help is appreciated )
> > but what approach to take would be a great help.
>
> > Meanwhile I am also searching google ;)
>
> > Thanking in anticipation.
>
> > - Vaibhav
>
> - start coding
> - get help from Google
> - for reference you might go tohttp://w3schools.com/js/default.asp

> - when you have coded something, and get weird errors, post what you
> have made, and ask questions...
>
> --
> Luuk

Thanx for your reply but I just wanted to know where to start
looking..!

Luuk

unread,
Oct 17, 2009, 6:07:32 AM10/17/09
to
vaib schreef:

http://w3schools.com/js/default.asp is a nice starting point...

it has a "Start learning JavaScript now!" section tooo ;-)

--
Luuk

vaib

unread,
Oct 17, 2009, 6:37:36 AM10/17/09
to
> http://w3schools.com/js/default.aspis a nice starting point...

>
> it has a "Start learning JavaScript now!" section tooo ;-)
>
> --
> Luuk

I've gone through it.

rf

unread,
Oct 17, 2009, 6:53:57 AM10/17/09
to

> I've gone through it.

Just be aware that just like the rest of the w3schools site it is sometimes
wildly inaccurate. For example: from that afforementioned page:
"Javascript can be used to detect the visitor's browser".
No, it cannot be used to do this. Not at all reliably.


vaib

unread,
Oct 17, 2009, 7:18:19 AM10/17/09
to
> >>http://w3schools.com/js/default.aspisa nice starting point...

>
> >> it has a "Start learning JavaScript now!" section tooo ;-)
> > I've gone through it.
>
> Just be aware that just like the rest of the w3schools site it is sometimes
> wildly inaccurate. For example: from that afforementioned page:
> "Javascript can be used to detect the visitor's browser".
> No, it cannot be used to do this. Not at all reliably.

Yes I know. It's only for the one looking to learn the ABC of
something. But thanx for responding.

vaib

unread,
Oct 17, 2009, 7:25:33 AM10/17/09
to
On Oct 17, 2:48 am, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
wrote:
> Le 10/16/09 7:58 PM, vaib a écrit :

<html>
<head>
<title>Some Experiments with JS</title>
<script type="text/javascript">
function Swap()
{
var AA = document.getElementById("A") ;
var BB = document.getElementById("B") ;
//var dup = AA.cloneNode(true);
var replaced = document.body.replaceChild(BB,AA);
//var replace2 = document.body.replaceChild(dup,BB);

}
</script>

</head>
<body>


<div ID="A" style="width:50%; background:lime; ">AAA</div>
<p> Some Paragraph here..! </p>
<div ID="B" style="width:50%; background:aqua; ">BBB</div>
<div>
<input type=button onClick="Swap()">
</div>
</body>
</html>


When I try the above code. It successfully replaces div "A" by div
"B" (as you can see through the replaceChild method) but the position
of div "A" is lost. So I am not able to put "A" in "B"'s place. Is
there some way to retain the positions ?

Thanx.

Thomas 'PointedEars' Lahn

unread,
Oct 17, 2009, 7:48:31 AM10/17/09
to
Luuk wrote:

> vaib schreef:


> http://w3schools.com/js/default.asp is a nice starting point...

It isn't.

> it has a "Start learning JavaScript now!" section tooo ;-)

The problem is that they they don't know what they are talking about.

Please trim your quotes. <http://jibbering.com/faq/#posting>

PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm> (404-comp.)

Luuk

unread,
Oct 17, 2009, 8:05:02 AM10/17/09
to
Thomas 'PointedEars' Lahn schreef:

> Luuk wrote:
>
>> vaib schreef:
>> http://w3schools.com/js/default.asp is a nice starting point...
>
> It isn't.

why post this?,
I did because the OP wanted a starting point,
and i think it is..

If you know a better starting point, than please SHARE

--
Luuk

SAM

unread,
Oct 17, 2009, 9:51:43 AM10/17/09
to
Le 10/17/09 1:25 PM, vaib a �crit :

>
> When I try the above code. It successfully replaces div "A" by div
> "B" (as you can see through the replaceChild method) but the position
> of div "A" is lost.

I think that it is the div B who is lost (since it is now A).


<html>
<head>
<title>Some Experiments with JS</title>
<script type="text/javascript">

function Swap(idDivA, idDivB)
{
var A, A1, B, B1;
A = document.getElementById(idDivA) ;
A1 = A.cloneNode(true);
B = document.getElementById(idDivB) ;
B1 = B.cloneNode(true);
A.parentNode.replaceChild(B1,A);
B.parentNode.replaceChild(A1,B);


}
</script>
</head>
<body>
<div ID="A" style="width:50%; background:lime;">AAA</div>
<p> Some Paragraph here..! </p>
<div ID="B" style="width:50%; background:aqua;">BBB</div>
<p> Some Paragraph here..! </p>

<div style="border:1px solid; padding:1em">
<div ID="C" style="background:yellow;">CCC</div>
</div>
<div>
<button onClick="Swap('A','B')">xchge A B</button>
<button onClick="Swap('C','B')">xchge C B</button>
<button onClick="Swap('A','C')">xchge A C</button>
</div>
</body>
</html>

--
sm

John G Harris

unread,
Oct 17, 2009, 10:13:02 AM10/17/09
to

He doesn't understand them, see
<http://www.merlyn.demon.co.uk/js-other.htm>,
"Semicolons and Newlines".

John
--
John Harris

Mike Duffy

unread,
Oct 17, 2009, 11:05:46 AM10/17/09
to
> Thomas 'PointedEars' Lahn schreef:

>> Luuk wrote:

>>> http://w3schools.com/js/default.asp is a nice starting point...

>> It isn't.

FWIW, I concur with Luuk. Granted, it may be a poor resource for those
asdvanced anough to already understand the difference between methods,
functions, properties, etc.

But is it a good "Javascript for Dummies" site. (It worked for me.)

Dr J R Stockton

unread,
Oct 17, 2009, 6:43:34 PM10/17/09
to
In comp.lang.javascript message <2fAM1$EuDd2...@J.A830F0FF37FB96852AD0
8924D9443D28E23ED5CD>, Sat, 17 Oct 2009 15:13:02, John G Harris
<jo...@nospam.demon.co.uk> posted:

>
>He doesn't understand them, see
> <http://www.merlyn.demon.co.uk/js-other.htm>,
> "Semicolons and Newlines".

You have never given a justification for that statement with enough
detail to make it understandable and therefore potentially refutable.
Mere blather is inadequate.

Why do you not instead write something of possible benefit to the OP -
such as this : ?
function Swap() { var AA, BB, T, F
AA = document.getElementById("A").style
BB = document.getElementById("B").style
if (AA.styleFloat) F = "styleFloat"
if (BB. cssFloat) F = "cssFloat"
T = AA[F] ; AA[F] = BB[F] ; BB[F] = T }

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)

John G Harris

unread,
Oct 18, 2009, 10:08:15 AM10/18/09
to
On Sat, 17 Oct 2009 at 23:43:34, in comp.lang.javascript, Dr J R
Stockton wrote:
>In comp.lang.javascript message <2fAM1$EuDd2...@J.A830F0FF37FB96852AD0
>8924D9443D28E23ED5CD>, Sat, 17 Oct 2009 15:13:02, John G Harris
><jo...@nospam.demon.co.uk> posted:
>>
>>He doesn't understand them, see
>> <http://www.merlyn.demon.co.uk/js-other.htm>,
>> "Semicolons and Newlines".
>
>You have never given a justification for that statement with enough
>detail to make it understandable and therefore potentially refutable.
>Mere blather is inadequate.
<snip>

As you've not been able to find the problem on your own I suppose I'd
better give you a hint. Consider this piece of code :

var a = 2;
var b, c;
if (a == 2) switch (a) { case 2: b = 5; break; } ; else b = 6;
alert(b);

Convince yourself that it contains a syntax error. Decide exactly what
the problem is. Now review the following sentence in your web page :

"Then every statement will be terminated by a semicolon."

John
--
John Harris

VK

unread,
Oct 18, 2009, 10:42:59 AM10/18/09
to
John G Harris wrote:
> As you've not been able to find the problem on your own I suppose I'd
> better give you a hint. Consider this piece of code :
>
>     var a = 2;
>     var b, c;
>     if (a == 2) switch (a) { case 2: b = 5; break; } ; else b = 6;
>     alert(b);
>
> Convince yourself that it contains a syntax error. Decide exactly what
> the problem is. Now review the following sentence in your web page :
>
> "Then every statement will be terminated by a semicolon."

Well, this sample doesn't prove the harm of semicolons omission
because if-else *statement" will be indeed terminated by a semicolon
in the tokenizer while semicolon insertion between if-else statement
*expressions* is an error the tokenizer would not do.

This group had its "aggressive purism" period including the immediate
decapitation for any semicolon missing :) At that period some samples
were found where missing explicit semicolon would lead to a unexpected
result. The cases were not numerous at all and rather... special...
yet there are of them if one search the archives.

vaib

unread,
Oct 18, 2009, 11:00:24 AM10/18/09
to
On Oct 17, 6:51 pm, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
wrote:
> Le 10/17/09 1:25 PM, vaib a écrit :

ya thats when you use the second replaceChild.

vaib

unread,
Oct 18, 2009, 11:03:45 AM10/18/09
to
On Oct 17, 8:05 pm, Mike Duffy <resp...@invalid.invalid> wrote:
> > Thomas 'PointedEars' Lahn schreef:
> >> Luuk wrote:
> >>>http://w3schools.com/js/default.aspis a nice starting point...

> >> It isn't.
>
> FWIW, I concur with Luuk. Granted, it may be a poor resource for those
> asdvanced anough to already understand the difference between methods,
> functions, properties, etc.
>
> But is it a good "Javascript for Dummies" site. (It worked for me.)

Sir can we just discuss the problem instead of evaluating w3schools.

vaib

unread,
Oct 18, 2009, 11:05:31 AM10/18/09
to

can we just discuss the problem instead of starting a sub thread on
semicolon usage ?

Message has been deleted

Thomas 'PointedEars' Lahn

unread,
Oct 18, 2009, 11:59:50 AM10/18/09
to
vaib wrote:

> Sir can we just discuss the problem instead of evaluating w3schools.

Mu.


PointedEars
--
Danny Goodman's books are out of date and teach practices that are
positively harmful for cross-browser scripting.
-- Richard Cornford, cljs, <cife6q$253$1$8300...@news.demon.co.uk> (2004)

Thomas 'PointedEars' Lahn

unread,
Oct 18, 2009, 12:00:57 PM10/18/09
to
vaib wrote:

> can we just discuss the problem instead of starting a sub thread on
> semicolon usage ?

Can you just get in informed where you are posting to, and accept that
Usenet is not a support Web forum but a text-based electronic medium of
discussion? You do not own the thread.

VK

unread,
Oct 18, 2009, 1:39:06 PM10/18/09
to
vaib wrote:
> can we just discuss the problem instead of starting a sub thread on
> semicolon usage ?

Are you still not answered? I did not read all posts in here as the
problem itself was not interesting to me. Sorry then, so OP was: "A


page where two DIVs are placed side by side and there's a button
below. On the click of the button the DIVs should exchange their

positions (of course, with everything in them also being exchanged). I
have to make it resolution free." As much as the task is described
that can be one of solutions:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<title>Demo</title>
<style type="text/css">
DIV#A {
position: absolute;
left: 4em; top: 4em;
width: 10em; height: 10em;
background-color: #FFFF00;
}
DIV#B {
position: absolute;
left: 18em; top: 4em;
width: 10em; height: 10em;
background-color: #00FF00;
}
P#menu {
position: absolute;
left: 4em; top: 18em;
}
</style>
<script type="text/javascript">

function swap() {
if (swap.originalPos) {
$('A').style.left = '18em';
$('B').style.left = '4em';
swap.originalPos = false;
}
else {
$('A').style.left = '4em';
$('B').style.left = '18em';
swap.originalPos = true;
}
}
swap.originalPos = true;

function $(id) {
return document.getElementById(id);
}
</script>
</head>
<body>
<div id="A"><p>A</p></div>
<div id="B"><p>B</p></div>
<p id="menu"><button type="button" onclick="swap();">swap</button></
p></body>
</html>

Thomas 'PointedEars' Lahn

unread,
Oct 18, 2009, 2:18:33 PM10/18/09
to
VK wrote:

> vaib wrote:
>> can we just discuss the problem instead of starting a sub thread on
>> semicolon usage ?
>
> Are you still not answered? I did not read all posts in here as the

> problem itself was not interesting to me. Sorry then, so OP was: [...]

We all have downloaded and read the OP already, thank you very much.

> As much as the task is described that can be one of solutions:
>
> <!DOCTYPE html>

Will you ever learn?

> [...]


> function swap() {
> if (swap.originalPos) {
> $('A').style.left = '18em';
> $('B').style.left = '4em';
> swap.originalPos = false;
> }
> else {
> $('A').style.left = '4em';
> $('B').style.left = '18em';
> swap.originalPos = true;
> }
> }

Hopelessly inefficient, hard-to-maintain and hard-to-debug, idiotic coding;
so very typical for you.

function swap()
{
var a = document.getElementById("A");
var b = document.getElementById("B");
if (a && b)
{
var aPos = a.style.left;
a.style.left = b.style.left;
b.style.left = aPos;
}
else
{
/* DEBUG */
}
}

However, this would require either inline styles or computed values, so
I would rather swap CSS class names instead, e.g.:

function swap()
{
var a = document.getElementById("A");
var b = document.getElementById("B");
if (a && b)
{
var aClassName = a.className;
a.className = b.className;
b.className = aClassName;
}
else
{
/* DEBUG */
}
}

> [...]


> <p id="menu"><button type="button" onclick="swap();">swap</button></
> p></body>

Unnecessarily complicated and incompatible. For a button with plain text
caption, one simply uses <input type="button" value="Swap" ...>. And that
button should be generated with scripting in any case.

John G Harris

unread,
Oct 18, 2009, 3:25:07 PM10/18/09
to
On Sun, 18 Oct 2009 at 07:42:59, in comp.lang.javascript, VK wrote:
>John G Harris wrote:
>> As you've not been able to find the problem on your own I suppose I'd
>> better give you a hint. Consider this piece of code :
>>
>> � � var a = 2;
>> � � var b, c;
>> � � if (a == 2) switch (a) { case 2: b = 5; break; } ; else b = 6;
>> � � alert(b);
>>
>> Convince yourself that it contains a syntax error. Decide exactly what
>> the problem is. Now review the following sentence in your web page :
>>
>> "Then every statement will be terminated by a semicolon."
>
>Well, this sample doesn't prove the harm of semicolons omission

Not surprising as this sub-thread is about semicolon insertion, not
semicolon omission.


>because if-else *statement" will be indeed terminated by a semicolon
>in the tokenizer while semicolon insertion between if-else statement
>*expressions* is an error the tokenizer would not do.

<snip>

An if or if-else statement is *never* terminated by a semicolon. It's
terminated by a nested, internal, statement. Also, the only expression
is the if-condition.

If you don't understand that then you don't understand the language. Nor
do you understand Algol, Pascal, Simula, C, C++, Java, and C# which all
have the same rules for if statements.

John
--
John Harris

VK

unread,
Oct 18, 2009, 5:38:38 PM10/18/09
to
John G Harris wrote:
> >> As you've not been able to find the problem on your own I suppose I'd
> >> better give you a hint. Consider this piece of code :
>
> >>     var a = 2;
> >>     var b, c;
> >>     if (a == 2) switch (a) { case 2: b = 5; break; } ; else b = 6;
> >>     alert(b);
>
> >> Convince yourself that it contains a syntax error. Decide exactly what
> >> the problem is. Now review the following sentence in your web page :
>
> >> "Then every statement will be terminated by a semicolon."
>
> >Well, this sample doesn't prove the harm of semicolons omission

And repeating again - it does not, and that was the reason of my
comment.

> >because if-else *statement" will be indeed terminated by a semicolon
> >in the tokenizer while semicolon insertion between if-else statement
> >*expressions* is an error the tokenizer would not do.

> An if or if-else statement is *never* terminated by a semicolon. It's


> terminated by a nested, internal, statement. Also, the only expression
> is the if-condition.
>
> If you don't understand that then you don't understand the language. Nor
> do you understand Algol, Pascal, Simula, C, C++, Java, and C# which all
> have the same rules for if statements.

I do "speak" Perl, JavaScript, AutoLISP, VBA BASIC, Java (applet level
mainly). I still do not understand the point you were trying to make
to Dr.Stockton and now making to me. First of all, JavaScript syntax
does require semicolons at all needed places. The other thing is that
the tokenizer does automatically insert missing semicolons on the fly
so the parser gets syntactically correct instructions even if the
programmer was too lazy to type them in. And the main rule of the auto-
correction is that the result always has to be grammatical. This way
it will not insert ; after a=1 here
if (cond)
a=1
else
a=2
not because "if-else statement is *never* terminated by a semicolon.
It's> terminated by a nested, internal, statement". It will not
insert ; because the stay alone instruction
else a=2;
is not grammatical. For the same grammatical reason the tokenizer will
not have troubles with say
{property: f()}
is this labeled statement in a block? is this object literal? of
course an object literal, otherwise it is not grammatical. I don't
know if it is so in "Algol, Pascal, Simula, C, C++, Java, and C#" but
in JavaScript it is this way and no other way around. You may find
interesting as well "Quibbling Over Semicolons" by Eric Lippert:
http://blogs.msdn.com/ericlippert/archive/2004/02/02/quibbling-over-semicolons.aspx


VK

unread,
Oct 18, 2009, 5:53:12 PM10/18/09
to
VK wrote:
> > <!DOCTYPE html>

Thomas 'PointedEars' Lahn wrote:
> Will you ever learn?

Will you?
http://groups.google.com/group/comp.lang.javascript/msg/f4d3681cd2960ea5
Very slowly one more time: I am posting HTML5 valid code. If you don't
like HTML5 it is your problem. If you declare that W3C Validator green-
sign validated code is still not valid until Thomas 'PointedEars' Lahn
admitted it as valid then it is your problem also (and a big one I
would say).

Thomas 'PointedEars' Lahn wrote:
> Hopelessly inefficient, hard-to-maintain and hard-to-debug, idiotic coding;
> so very typical for you.

[...]

etc. void blah-blah-blah snipped

I need to sort out all chars in range \u0100 - \u2000 as a part of a
complex case-insensitive regexp. Is it doable or do I need to split
the regexp on two:
[\u0100 - \u2000]
then case-insensitive match part
? If you have time in your hand you may answer it in the "i madness"
thread.

SAM

unread,
Oct 18, 2009, 6:06:26 PM10/18/09
to
Le 10/18/09 5:00 PM, vaib a �crit :

> On Oct 17, 6:51 pm, SAM <stephanemoriaux.NoAd...@wanadoo.fr.invalid>
> wrote:
>> Le 10/17/09 1:25 PM, vaib a �crit :

>>
>>> When I try the above code. It successfully replaces div "A" by div
>>> "B" (as you can see through the replaceChild method) but the position
>>> of div "A" is lost.
>>
>> I think that it is the div B who is lost (since it is now A).
>
> ya thats when you use the second replaceChild.

Of course as at this time it no more exists
so you have to move (replace with) clones of the divs.
Clones must both exist before replacing.

did you read and try the example of code I gave ?
(normaly working with any div, no importance if divs to xchange are in
another div or not)

Dr J R Stockton

unread,
Oct 18, 2009, 3:48:23 PM10/18/09
to
In comp.lang.javascript message <S+Zj6ZDP...@J.A830F0FF37FB96852AD0
8924D9443D28E23ED5CD>, Sun, 18 Oct 2009 15:08:15, John G Harris

<jo...@nospam.demon.co.uk> posted:
>On Sat, 17 Oct 2009 at 23:43:34, in comp.lang.javascript, Dr J R
>Stockton wrote:
>>In comp.lang.javascript message <2fAM1$EuDd2...@J.A830F0FF37FB96852AD0
>>8924D9443D28E23ED5CD>, Sat, 17 Oct 2009 15:13:02, John G Harris
>><jo...@nospam.demon.co.uk> posted:
>>>
>>>He doesn't understand them, see
>>> <http://www.merlyn.demon.co.uk/js-other.htm>,
>>> "Semicolons and Newlines".
>>
>>You have never given a justification for that statement with enough
>>detail to make it understandable and therefore potentially refutable.
>>Mere blather is inadequate.
> <snip>
>
>As you've not been able to find the problem on your own I suppose I'd
>better give you a hint. Consider this piece of code :
>
> var a = 2;
> var b, c;
> if (a == 2) switch (a) { case 2: b = 5; break; } ; else b = 6;
> alert(b);
>
>Convince yourself that it contains a syntax error.

IE, Firefox and Opera agree that does; that's convincing enough.

> Decide exactly what
>the problem is. Now review the following sentence in your web page :
>
>"Then every statement will be terminated by a semicolon."

But I was writing about valid JavaScript, not JavaScript with a syntax
error.

Obviously adding more end-of-lines semicolons will not help.

That code becomes valid by removing the semicolon before "else".

Aesthetically, because a switch statement is complicated, I would
enclose it in {} or newlines or both, but that is only visually helpful.

Try reading my page more carefully. Then you might also see such as the
error in the previous section "White Space".

Dr J R Stockton

unread,
Oct 18, 2009, 6:49:58 PM10/18/09
to
In comp.lang.javascript message <4029210.E...@PointedEars.de>,
Sun, 18 Oct 2009 18:00:57, Thomas 'PointedEars' Lahn
<Point...@web.de> posted:
>vaib wrote:
>

> You do not own the thread.

Neither do you, you arrogant hypocrite. Read FAQ 1.3 B 3.

>PointedEars

Richard Cornford

unread,
Oct 18, 2009, 7:15:33 PM10/18/09
to
> type them in. And the main rule of the auto-correction is that

> the result always has to be grammatical. This way it will not
> insert ; after a=1 here
> if (cond)
> a=1
> else
> a=2

On the contrary, inserting a semi-colon in that location is required.
The statement following the closing parenthesis of the - if - expression
is an ExpressionStatement and ExpressionStatements are semicolon
terminated (ECMA 262 3rd Ed. Section 12.4) (in contrast to
SwitchStatements, which are not).

And if you load this:-

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<pre>
<script type="text/javascript">

function x(){


if (cond)
a=1
else
a=2
}

document.write(x.toString());
</script>
</pre>
</body>
</html>

- into a browser that genuinely decomplies functions when it creates the
string representation of them, such as Firefox 3, you can even see the
added semicolons.

And what is more, if you attempt to load:-

if (cond) a=1 else a=2

- you will get a syntax error along the lines of IE's "Expected ';'" or
Firefox's "missing ; before statement" (which is technically incorrect
(the thing that follows the needed semicolon is not a statement), but
that us normal for Firefox's error messages).

> not because "if-else statement is *never* terminated by a semicolon.
> It's> terminated by a nested, internal, statement". It will not
> insert ; because the stay alone instruction
> else a=2;
> is not grammatical.

The statement:-

if (cond) a=1; else a=2;

- is grammatical (as are all possible variants resulting form the
insertion of whitespace and/or line terminators between the tokens).

> For the same grammatical reason the tokenizer will
> not have troubles with say
> {property: f()}
> is this labeled statement in a block? is this object literal? of
> course an object literal,

In isolation it is a Block statement, containing a labelled statement,
labelling a function call that represents and ExpressionStatement. And
an automatic semicolon insertion happens here, making the point. Load
this into Friefox 3:-

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<pre>
<script type="text/javascript">
function x(){
{property: f()}
}

document.write(x.toString());
</script>
</pre>
</body>
</html>

- and observe that the output is:-

function x() {
property:
f();
}

- and see not only the inserted semicolon but also that he redundant
block statement has been optimised away. If the code had been (or could
have been) interpreted as an object literal then the output would have
reflected that.

> otherwise it is not grammatical.

No, the Block statement, labelled statement and function call
ExpressionStatement are completely grammatical.

> I don't know if it is so in "Algol, Pascal, Simula, C, C++, Java,
> and C#" but in JavaScript it is this way and no other way around.

What you don't know is evident. In javascript it is the other way around
from what you are describing.

> You may find interesting as well "Quibbling Over Semicolons"
> by Eric Lippert:

Because that did sooo much to improve your understanding of the subject?

Richard.

VK

unread,
Oct 19, 2009, 7:06:29 AM10/19/09
to
Richard Cornford wrote:
> On the contrary, inserting a semi-colon in that location is required.
> The statement following the closing parenthesis of the - if - expression
> is an ExpressionStatement and ExpressionStatements are semicolon
> terminated (ECMA 262 3rd Ed. Section 12.4) (in contrast to
> SwitchStatements, which are not).

You know my highly skeptical attitude to the Books Of ECMA wording and
statements ("statements" in the common human language use sense). Yet
if we decided to quote the Books then let's us quote them right.
Chapter 12 Song 4 :) has nothing to do with the issue because in
if (cond) a=1
a=1 is not an ExpressionStatement. I am leaving on you the necessary
reductio ad absurdum steps with the starting rules:
1) "an ExpressionStatement cannot start with an opening curly
brace" (Books of ECMA, Chapter 12, Song 4)
2) if (cond) {a=1} is a grammatically correct valid language
instruction

The relevant to the topic part would be Chapter 12, Song 5 ("The if
Statement") but it is so badly written that not really usable in the
practical sense yet still good for meditations :)

The correct explanation is that if-else statement has implied {block}
part after each part of the statement. And besides auto-insertion of
semicolons the tokenizer has other error-correction mechanics in it,
and among it - an auto block wrapping for *simple* if-else cases.
Other words when meeting
"if (cond) a=1 LINE_TERMINATOR else a=0 LINE_TERMINATOR"
tokenizer brings it to the form
if (cond) {a=1;} else {a=0;}"
and this goes to the parser. You seem to relay on Firefox back-to-
source reverse tools such as toSource: which is a very dangerous thing
as it is merely a debugging tool left by Gecko developers - and it
outputs what they wanted for their internal code tracking needs. Yet
one may try this as it is pretty close to what the actual bytecode
does:

function demo() {
if (false) window.alert(arguments.callee.toSource()+'\n1');
else window.alert(arguments.callee.toSource()+'\n2');
}
demo();

I do understand the excitement of purists around if-else case as it
produces so much wanted "missing ; before statement" error message to
show to everyone. As a side note I want to state that personally I
never rely on error correction mechanics and I always use explicit
block syntax even for single statement:
if (cond) {a=1;} else {a=0;}
and I strongly encourage anyone to do the same. Yet let do not mix the
actual look-ahead mechanics with badly written descriptions of this
mechanics and some misleading error messages.
IF (true) a=1
else a=0

true else false

etc. are still "missing ; before statement" but it proves nothing (nor
does it mean a lot)

> The statement:-
>
> if (cond) a=1; else  a=2;
>
> - is grammatical

As it was explained earlier it is not, because there is not stay alone
operator or expression "else", only "else" as a part of if-else block.
But the semicolon helps the tokenizer look-ahead mechanics to decrypt
the possible author's intentions so it produces grammatically correct
if (cond) {a=1;} else {a=2;}

Sorry, but it is a complete nonsense. Are you implying that any {prop:
f()} is interpreted as
label:
function call
and 99.99% of existing code is in rewrite emergency? You cannot be
serious.

function f() {
return 'bar';
}
window.alert({foo:f()}.foo); // 'bar'

Richard Cornford

unread,
Oct 19, 2009, 9:03:19 AM10/19/09
to
On Oct 19, 12:06 pm, VK wrote:
> Richard Cornford wrote:

Didn't you want to quote those statements of yours that I was replying
to? I cannot say I am suppressed, but it is not like you to be that
embarrassed by being that wrong. Editing without marking your edits is
disingenuous regardless of your reasons for doing it.

>> On the contrary, inserting a semi-colon in that location is
>> required. The statement following the closing parenthesis of
>> the - if - expression is an ExpressionStatement and
>> ExpressionStatements are semicolon terminated (ECMA 262 3rd
>> Ed. Section 12.4) (in contrast to SwitchStatements, which
>> are not).
>
> You know my highly skeptical attitude to the Books Of ECMA
> wording and statements ("statements" in the common human
> language use sense).

I know that you have difficulty understanding the spec, and would
rather construct an elaborate fiction of your own rather than
attempting to understand it.

> Yet if we decided to quote the Books then let's us quote them
> right. Chapter 12 Song 4 :) has nothing to do with the issue
> because in
> if (cond) a=1
> a=1 is not an ExpressionStatement.

The - a=1 - in if (cond) a=1 - absolutely is an ExpressionStatement.

> I am leaving on you the necessary
> reductio ad absurdum steps with the starting rules:
> 1) "an ExpressionStatement cannot start with an opening curly
> brace" (Books of ECMA, Chapter 12, Song 4)

Fine, - a=1 - does not start with either an opening curly brace or the
- function - keyword, so it is not precluded from being an
ExpressionStatement by that.

> 2) if (cond) {a=1} is a grammatically correct valid language
> instruction

Yes, in that case the closing parenthesis after the - if - condition
expression is followed by a Block expression (ECMA 262 3rd Ed. Section
12.1). The StatmentList inside that Block statement is a single
ExpressionStatement consisting of - a=1- but that has no relevance for
an - if - statement that does not include any Block statements.

> The relevant to the topic part would be Chapter 12, Song 5 ("The
> if Statement") but it is so badly written that not really usable
> in the practical sense yet still good for meditations :)

Section 12.5 is entirely understandable. The two productions for - if
- are:-

if ( Expression ) Statement else Statement

- and:-

if ( Expression ) Statement

- which means that the conditional expression can be anything that
qualifies as an Expression, but it must be parenthesised, and you can
substitute anything that qualifies as a Statement where the words
"Statement" appear. Which could be a Block statement, a
SwitchStatement or an ExpressionStatement, or any of the others
available in the language, including another IfStatement.

> The correct explanation

Here comes the 'made up off the top of your head' fiction.

> is that if-else statement has implied {block}
> part after each part of the statement.

Well, no.

> And besides auto-insertion of
> semicolons the tokenizer has other error-correction mechanics
> in it,

There are no other error correcting mechanisms specified, and while
syntax extensions are possible they are not needed to explain anything
that is occurring here.

> and among it - an auto block wrapping

"Auto block wrapping" being your fiction of the day.

> for *simple* if-else cases.
> Other words when meeting
> "if (cond) a=1 LINE_TERMINATOR else a=0 LINE_TERMINATOR"
> tokenizer brings it to the form
> if (cond) {a=1;} else {a=0;}"

Then why is:-

if (cond) a=1 else a=0

-(without line terminators) - a syntax error when:-

if (cond) { a=1 } else { a=0}

- is not? If some sort of implied Block insertion was going on why
does it not happen in the first case. I suppose your next fabrication
would be the suggestion that this can only happen if the - if -
statement is spread across multiple lines, but going back to John G
Harris' original example, why is:-

if (a == 2)
switch (a) { case 2: b = 5; break; } ;
else
b = 6;

- a syntax error when:-

if (a == 2) {
switch (a) { case 2: b = 5; break; } ;
} else {
b = 6;
}

- is not?

This "auto block wrapping" does not appear to be doing a very good job
of explaining what is going on here. Unsurprising as you made it up on
the spot.

> and this goes to the parser. You seem to relay on Firefox

> back-to-source reverse tools such as toSource:

No, I just observed that they do show the automatically inserted
semicolons, which makes them useful if debating when and were
semicolons are automatically inserted.

> which is a very dangerous thing as it is merely a debugging
> tool left by Gecko developers - and it outputs what they
> wanted for their internal code tracking needs.

That does not stop what it outputs from corresponding with the
specified behaviour.

> Yet one may try this as it is pretty close to what the actual
> bytecode does:
>
> function demo() {
> if (false) window.alert(arguments.callee.toSource()+'\n1');
> else window.alert(arguments.callee.toSource()+'\n2');}
>
> demo();

To what end? All that shows is that the complier is smart enough to
recognise that - if (false ) - is the condition there is no point in
having anything but the contents of the - else - branch and the other
code is unreachable. A reasonable optimisation.

> I do understand the excitement of purists around if-else case
> as it produces so much wanted "missing ; before statement" error
> message to show to everyone.

You are becoming incoherent again.

> As a side note I want to state that personally I
> never rely on error correction mechanics and I always use explicit
> block syntax even for single statement:
> if (cond) {a=1;} else {a=0;}
> and I strongly encourage anyone to do the same. Yet let do not
> mix the actual look-ahead mechanics with badly written
> descriptions of this mechanics and some misleading error messages.

All we have seen here is the application of the rules for automatic
semicolon insertion, as specified. Yet you have dreamt up "error
correction mechanics", " look-ahead mechanics" and "misleading error
messages" as part of your bullshit explanation.

> IF (true) a=1
> else a=0

Where the missing semicolon is the one that should terminate the
ExpressionStatement - IF ( true) -, which is a function call.

> true else false

Where the missing semicolon is the one that should terminate the
ExpressionStatement - true -, which is worthless but legal.

> etc. are still "missing ; before statement" but it proves nothing
> (nor does it mean a lot)

It means that your code contains syntax errors, and probably points
you to where those errors are located.

>> The statement:-
>
>> if (cond) a=1; else a=2;
>
>> - is grammatical
>
> As it was explained earlier it is not,

It is. That code fully stratifies the ECMA 262 rules. The ability to
load that code into any javascript environment without error or
complaint pretty much guarantees that it is free of syntax errors.

> because there is not stay alone operator or expression "else",
> only "else" as a part of if-else block.

You asserted that in:-

if (cond )
a=1
else
a=2

- the parser (though you actually incorrectly attributed the behaviour
to the tokenise (see the opening sentence of Section 7.9.1)) could not
add a semicolon after the - a=1 -. However, as I said, no only can a
semicolon be automatically added, but it must be automatically added.
That addition corrects the first Statement in;-

if ( Expression ) Statement else Statement

- so it really has nothing to do with - else - being part of the
structure that contains that Statement.

> But the semicolon helps the tokenizer look-ahead mechanics to decrypt
> the possible author's intentions

"Look-ahead mechanics", "decrypt", "possible author's intentions". I
would suggest that you couldn't make this stuff up, except that you
clearly have.

> so it produces grammatically correct
>
> if (cond) {a=1;} else {a=2;}

Why would it do that when:-

if (cond )
a=1;
else
a=2;

- is all that is necessary, and achievable only by the applying of the
automatic semi-colon insertion rules.


>>> For the same grammatical reason the tokenizer will
>>> not have troubles with say
>>> {property: f()}
>>> is this labeled statement in a block? is this object literal?

>>> of course an object literal, otherwise it is not grammatical.

>> In isolation it is a Block statement, containing a labelled statement,

^^^^^^^^^^^^


>> labelling a function call that represents and ExpressionStatement.
>> And an automatic semicolon insertion happens here, making the
>> point.

<snip>


>> - and observe that the output is:-
>
>> function x() {
>> property:
>> f();
>
>> }
>

>> - and see not only the inserted semicolon but also that the


>> redundant block statement has been optimised away. If the code
>> had been (or could have been) interpreted as an object literal
>> then the output would have reflected that.
>
> Sorry, but it is a complete nonsense.

How could you possibly tell?

> Are you implying that any {prop:
> f()} is interpreted as
> label:
> function call

No, I am saying that in isolation such a construct is interpreted in
exactly that way. You mentioned yourself earlier that an Expression
Statement cannot start with an opening curly brace. That is to prevent
object literals being ambiguous with Block statements, so in a context
where statements are expected (which will always be the case when the
construct is in isolation) the opening curly brace can only be
interpreted as starting a Block statement.

When you asserted that - {property: f()} - would be interpreted as an
object literal you provided no context that would force such an
interpretation, and the 'default' interpretation certainly is not as
an object literal.

> and 99.99% of existing code is in rewrite emergency? You cannot
> be serious.

I can be serious, but it tends to go right over your head when I am.

> function f() {
> return 'bar';}
>
> window.alert({foo:f()}.foo); // 'bar'

The items in an ArgumentsList are AssignmentExpressions (and it makes
no sense to try to use a Statement as an argument anyway), so in that
context - {foo:f()} - has to be interpreted as an object literal. When
you were asserting that - {property: f()} - had to interpreted as an
object literal you provided no context, but instead asserted that the
alternative, Block containing label statement, was not "grammatical".
While in reality, without context, the interpretation is going to be
as a Block, and the contract is completely legal under that
interpretation.

Richard.

VK

unread,
Oct 19, 2009, 11:13:38 AM10/19/09
to
Richard Cornford wrote:

[...]

> When you asserted that - {property: f()} - would be interpreted as an
> object literal you provided no context that would force such an
> interpretation, and the 'default' interpretation certainly is not as
> an object literal.

And that is extremely interesting.

First of all you are completely right, a simple test shows that
{ key1 : "value1"}
is interpreted as a block of statements with a single labeled
statement in it, and not as an stay-alone object initialization.
Respectively
{ "key1" : "value1"}
leads to syntax error because label literal cannot be quoted.

That implies that JSON is not exactly "based on a subset of the
JavaScript Programming Language, Standard ECMA-262 3rd Edition -
December 1999" as http://json.org states because its object data
structures are not JavaScript syntax compatible per se as their key
values have to be quotes by specs. They become JavaScript syntax
compatible only if used in the right side of assignments. IMHO that
should be mentioned somewhere on the page.

VK

unread,
Oct 19, 2009, 11:24:56 AM10/19/09
to
VK wrote:
> That implies that JSON is not exactly "based on a subset of the
> JavaScript Programming Language, Standard ECMA-262 3rd Edition -
> December 1999" ashttp://json.orgstates because its object data

> structures are not JavaScript syntax compatible per se as their key
> values have to be quotes by specs. They become JavaScript syntax
> compatible only if used in the right side of assignments. IMHO that
> should be mentioned somewhere on the page.

I just narrowed and fixed a set of highly spurious syntax errors all
caused by this context-dependent language rules violation in JSON in
stay-alone data files. Can I buy you a beer or something?! :)

Richard Cornford

unread,
Oct 19, 2009, 11:42:31 AM10/19/09
to
On Oct 19, 4:13 pm, VK wrote:
> Richard Cornford wrote:
> [...]
>> When you asserted that - {property: f()} - would be interpreted
>> as an object literal you provided no context that would force
>> such an interpretation, and the 'default' interpretation
>> certainly is not as an object literal.
>
> And that is extremely interesting.

That probably depends on which side of understanding the language's
syntax rules you are observing from.

> First of all you are completely right,

And you have been guilty of making things up off the top of your head
again.

> a simple test shows that

That would be a test like the one I posted earlier, and to which you
responded "Sorry, but it is a complete nonsense".

> { key1 : "value1"}
> is interpreted as a block of statements with a single labeled
> statement in it, and not as an stay-alone object initialization.
> Respectively
> { "key1" : "value1"}
> leads to syntax error because label literal cannot be quoted.

Or more precisely because the label in a LabelledStatement is an
Identifier and a string literal is not an Identifier.

> That implies that JSON is not exactly "based on a subset of the
> JavaScript Programming Language, Standard ECMA-262 3rd Edition -
> December 1999"

No it doesn't. It really has nothing to do with JSON.

> as http://json.orgstates because its object data


> structures are not JavaScript syntax compatible

Yes they are.

> per se as their key
> values have to be quotes by specs.

Using string literals to provide the property names in an object
literal is valid javascript syntax.

> They become JavaScript syntax
> compatible only if used in the right side of assignments.

JSON is subset of javascript object literal notation regardless. JSON
is a text format for data exchange, so there is no real sense in "the
right hand side of assignments" where it is concerned. If you take a
JSON text and insert it into javascript source code then you would
only get away with that where its particular subset is applicable.
Object literal source text will be interpreted as an object literal in
all locations where an Expression is allowed, so, for example, as an
argument to a function call.

Data in JSON format is usually acquired in the form of a string value,
and so is independent of the source text of the code that employs it.

> IMHO that
> should be mentioned somewhere on the page.

Your opinions remain utterly worthless.

Richard.

VK

unread,
Oct 19, 2009, 12:16:23 PM10/19/09
to
VK wrote:
>> as http://json.orgstates because its object data
>> structures are not JavaScript syntax compatible

Richard Cornford wrote:
> Yes they are.

Now you are definitely kidding.

{"key1":"value1"}
structure is a valid JSON object data but it is not JavaScript syntax
compatible for the above spelled reasons and leads to "invalid label"
syntax error. By creating the assignment context like
var obj = {"key1":"value1"}
we are masking this potential error and successfully instantiating obj
over assignment. If - as many others - we are using JavaScript allowed
shortcut without quotes around the key name then we also masking this
ticking bomb:
{"key1":"value1"}

And
var obj = eval( '{key1:"value1"}' );
window.alert(typeof obj); // string
?

And
var obj = eval( '{"key1":"value1"}' );
// syntax error "invalid label"
?

And
var obj = eval('{"key1":"value1", "key2" : "value2"}');
// syntax error "invalid label"
?

And so on? I did over last hours more than planned for the week -
grace to you and thank you again.


Richard Cornford

unread,
Oct 19, 2009, 1:19:14 PM10/19/09
to
On Oct 19, 5:16 pm, VK wrote:
> VK wrote:
>>> ashttp://json.orgstatesbecause its object data

>>> structures are not JavaScript syntax compatible
> Richard Cornford wrote:

Why is it that cannot even manage to do the simplest things correctly?
The attributions belong at the top, and the number of chevrons that
precede them should be precisely one less than the number of chevrons
that mark the quotes that each attribution refers to.

>> Yes they are.
>
> Now you are definitely kidding.

No I am not. There are plenty of constructs that "syntax
compatible" (as you put it) that cannot just be dropped into source
code at whim with any expectation that the outcome will not be a
syntax error. For example, we have seen that - key1: - is fine for
labelling a statement, and to declare a property name in an object
literal but put it in an arguments list and you have a syntax error.
However, - key1: - is still a subset of javascript syntax regardless
of that.

> {"key1":"value1"}
> structure is a valid JSON object data but it is not JavaScript
> syntax compatible for the above spelled reasons

It is fine as javascript source code, it is just the source code for
an Expression not a Statement.

> and leads to "invalid label"
> syntax error.

Only if you do not use it in a context appropriate for an Expression.

> By creating the assignment context like
> var obj = {"key1":"value1"}
> we are masking this potential error

There is no potential error, particularly as asserting an object
literal is as worthless as writing:-

true;

> and successfully instantiating obj
> over assignment. If - as many others - we are using JavaScript
> allowed shortcut without quotes around the key name then we also
> masking this ticking bomb:
> {"key1":"value1"}

An expression statement taking the form:-

({ key1 : "value"});

- is utterly worthless as the resulting object literal is then
inaccessible. If you are already writing worthless code then having:-

{ key1 : "value"}

- interpreted as a block statement containing a labelled statement is
not going to make anything any worse.

> And
> var obj = eval( '{key1:"value1"}' );
> window.alert(typeof obj); // string
> ?
>
> And
> var obj = eval( '{"key1":"value1"}' );
> // syntax error "invalid label"
> ?
>
> And
> var obj = eval('{"key1":"value1", "key2" : "value2"}');
> // syntax error "invalid label"
> ?

But the - eval - function evaluates its string arguments as javascript
Programs, and the two structures that can make up a Program as
Statements and FunctionDeclarations. Your string arguments are clearly
not FunctionDeclarations so it should not be surprising if they get
interpreted as a Statement. And as has already been seen, an initial
opening curly brace in a Statement context can only be the beginning
of a Block statement. Whatever follows the brace can then only be
acceptable content for a Block statement or a syntax error, either way
it is never going to be an object literal as the only form of
statement that can consist of an Expression is an ExpressionStatement
and they are forbidden from starting with an opening brace.

Of course the 'solution' to the eval-ing JSON strings issues is a well
known as it is obvious (at least to anyone who understands the
language). You explicitly parenthesise the JSON expression and then
the result can be an ExpressionStatement because it no longer starts
with an opening brace (and that is never ambiguous with a Block as
statements are not allowed (directly, as they may still appear in the
bodies of contained function expressions) inside parenthesise). So:-

var obj = eval( '(' + JSON_String + ')' );

> And so on? I did over last hours more than planned for the
> week - grace to you and thank you again.

It remains pretty hard to believe that anyone is fool enough to employ
you to write computer software. The amount of time you must waste as a
result of taking the things in your head seriously is unimaginable.

Richard.

VK

unread,
Oct 19, 2009, 1:42:09 PM10/19/09
to
Richard Cornford wrote:
> It remains pretty hard to believe that anyone is fool enough to employ
> you to write computer software.

For the sake of fairness I need to note that over all these years I
didn't see yet a single finished program from you (commented code
snippets and test samples discounted). The only functional application
with a pronounced objective I know is your "Table Body Scroller" made
back in 2004:
http://web.archive.org/web/20040803193354/http://www.litotes.demon.co.uk/example_scripts/tableScroll.html
I am not stating that you cannot write programs. Most probably any
program you would write would become a new word in the programming and
a new stage in the programming theory. I am not denying anything of
that, but simply criticizing someone's else products without showing
anything of your own tends to be on the hypocrisy side.

> The amount of time you must waste as a
> result of taking the things in your head seriously is unimaginable.

As you wish. Assuming the world is full of fulls and I am hugely
capitalizing on it. It is not true but as you wish.

And thank you again for your great hint about stay alone blocks, even
if you are unable to see why so great and how so great it was.

Thomas 'PointedEars' Lahn

unread,
Oct 19, 2009, 2:30:19 PM10/19/09
to
VK wrote:

> VK wrote:
>>> as http://json.orgstates because its object data
>>> structures are not JavaScript syntax compatible
>
> Richard Cornford wrote:

In Usenet, that line belongs on the top of all the quotations, in order to
make it easy to quote that later. You have been told before numerous times.

>> Yes they are.
>
> Now you are definitely kidding.

No, he is not.



> {"key1":"value1"}
> structure is a valid JSON object data but it is not JavaScript syntax
> compatible for the above spelled reasons and leads to "invalid label"
> syntax error.

Only if used in a context where `{'...`}' are parsed as delimiters of a
/Block/ statement and consequently `"key": "value"' as a
/LabelledStatement/, e.g.:

/Program/
→ /SourceElements/
→ /SourceElement/
→ /Statement/
→ /Block/
→ { /StatementList/ }
→ { /Statement/ }
→ { /LabelledStatement/ }
→ { /Identifier/ : /Statement/ }
[ES3F, 12.1]

Richard explained that to you in greater detail; but obviously, and
unsurprisingly, you have not been paying attention.

> By creating the assignment context like
> var obj = {"key1":"value1"}
> we are masking this potential error

No, in that context it is parsed, as Richard already explained to you, as a
perfectly valid /AssignmentExpression/:

/Statement/
→ /VariableStatement/
→ var /VariableDeclarationList/ ;
→ var /VariableDeclaration/ ;
→ var /Identifier/ /Initialiser/ ;
→ var /Identifier/ = /AssignmentExpression/ ;
→ ...
→ var /Identifier/ = /ObjectLiteral/ ;
[ES3F, 11.3.1]

> and successfully instantiating obj over assignment.

Whatever that is supposed to mean.

> If - as many others - we are using JavaScript allowed
> shortcut without quotes around the key name then we also masking this
> ticking bomb:
> {"key1":"value1"}

You don't know what you are talking about.



> And
> var obj = eval( '{key1:"value1"}' );
> window.alert(typeof obj); // string
> ?

Since the string value of eval() is (to be) parsed as a /Program/, what
looks like an /ObjectLiteral/ at first is in fact parsed as a /Block/
statement:

/Program/
→ /SourceElements/
→ /SourceElement/
→ /Statement/
→ /Block/
→ { /StatementList/ }
→ { /Statement/ }
→ { /LabelledStatement/ }
→ { /Identifier/ : /Statement/ }
→ { /Identifier/ : /ExpressionStatement/ }
→ { /Identifier/ : /Expression/ }
→ { /Identifier/ : /AssignmentExpression/ }
→ ...
→ { /Identifier/ : /Literal/ }
→ { /Identifier/ : /StringLiteral/ }

And the result of a /Program/ is the result of the evaluation of its
/SourceElements/. [ES3F, 15.1.2.1, 14 pp.]

A simple workaround is to put the supposed-to-be Object initializer in
parentheses -- eval('({key1:"value1"})'); -- which causes it to be parsed as
follows:

/Program/
→ /SourceElements/
→ /SourceElement/
→ /Statement/
→ /ExpressionStatement/
→ /Expression/
→ ( /Expression/ )
→ ...
→ ( /ObjectLiteral/ )

A less simple and more expensive workaround -- but I have seen it before --
is using brackets:

/Program/
→ /SourceElements/
→ /SourceElement/
→ /Statement/
→ /ExpressionStatement/
→ /Expression/
→ ...
→ /ArrayLiteral/
→ [ /ElementList/ ]
→ [ /AssignmentExpression/ ]
→ ...
→ [ /ObjectLiteral/ ]



> And
> var obj = eval( '{"key1":"value1"}' );
> // syntax error "invalid label"
> ?

Since the string value of eval() is parsed as a /Program/, what looks like
an /ObjectLiteral/ at first is in fact parsed as a /Block/ statement, and
`"key1"' does not satisfy the criteria for a label since it needs to be an
/Identifier/:

/Program/
→ /SourceElements/
→ /SourceElement/
→ /Statement/
→ /Block/
→ { /StatementList/ }
→ { /Statement/ }
→ { /LabelledStatement/ }
→ { /Identifier/ : /Statement/ }
(→ Syntax error)
[ES3F, 15.1.2.1 pp.]



> And
> var obj = eval('{"key1":"value1", "key2" : "value2"}');
> // syntax error "invalid label"
> ?

(Granted, this one is a bit tricky.)

The comma is not parsed as delimiter between name-value pairs in an Object
initializer, but as a comma operator here. `"key1":"value"' must be parsed
as a /LabelledStatement/, and `"key1"' does not satisfy the criteria for a
label since it needs to be an /Identifier/:

/Program/
→ /SourceElement/
→ /Statement/
→ /Block/
→ { /StatementList/ }
→ { /StatementList/ /Statement/ }
→ { /Statement/ /Statement/ }
→ { /LabelledStatement/ /LabelledStatement/ }
→ { /Identifier/ : /Statement/ /LabelledStatement/ }
→ { /Identifier/ : /ExpressionStatement/ /LabelledStatement/ }
→ { /Identifier/ : /Expression/ /LabelledStatement/ }
→ { /Identifier/ : /Expression/ , /AssignmentExpression/
/LabelledStatement/ }
(→ Syntax error)
[ES3F, 15.1.2.1, ..., 11.14]

If the productions following `/LabelledStatement/ /LabelledStatement/' are
correct (the productions until that undoubtedly are), then the second syntax
error, at the second /LabelledStatement/, is ignored.

> And so on? I did over last hours more than planned for the week -

If you only tried to understand how the parser and grammar works, if you
only read the relevant parts of the Specification once, you would
understand; but then again, given your record of making up stories to fit
your arguments instead, probably not even then.


PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f806at$ail$1$8300...@news.demon.co.uk>

Thomas 'PointedEars' Lahn

unread,
Oct 19, 2009, 2:45:34 PM10/19/09
to
Richard Cornford wrote:

> But the - eval - function evaluates its string arguments as javascript
> Programs, and the two structures that can make up a Program as
> Statements and FunctionDeclarations.

JFTR: This wording is misleading. Per current Specification, eval() takes
only one argument (ES3F, 15.1.2.1). If that argument is a string value, the
return value of eval() is the result of the /Program/ that the string is
parsed as (potential syntax errors aside); if it is not a string value, the
return value of eval() is the argument itself (which makes `eval(42 + 23)'
and the like pointless calls).

Evertjan.

unread,
Oct 19, 2009, 3:20:59 PM10/19/09
to
Thomas 'PointedEars' Lahn wrote on 19 okt 2009 in comp.lang.javascript:

> Richard Cornford wrote:
>
>> But the - eval - function evaluates its string arguments as
>> javascript Programs, and the two structures that can make up a
>> Program as Statements and FunctionDeclarations.
>
> JFTR: This wording is misleading. Per current Specification, eval()
> takes only one argument (ES3F, 15.1.2.1). If that argument is a
> string value, the return value of eval() is the result of the
> /Program/ that the string is parsed as (potential syntax errors
> aside); if it is not a string value, the return value of eval() is the
> argument itself

Which is a difficult way of saying about the argument of eval():

1 if it is a string the string is executed and the result is returned.

2 if it is not a string the content is executed as if it were a string
and the result is returned.

so:

var abc = 3;
var r1 = eval(abc == 3); // true
var r2 = eval('abc == 3'); // true
var r3 = eval(abc); // 3
var r4 = eval('abc'); // 3ny

> (which makes `eval(42 + 23)' and the like pointless calls).

Not more so than a literal string eval like eval('42 + 23');
and a litteral string could be dynamic in serverside code sense:

<% 'serverside JS assumed under ASP
var x;
if (b) x = 'new Date();'
else x = 17;
%>

var r5 = eval('<% = x %>'); // returns the local date or 17


--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)

John G Harris

unread,
Oct 19, 2009, 3:22:15 PM10/19/09
to
On Sun, 18 Oct 2009 at 20:48:23, in comp.lang.javascript, Dr J R
Stockton wrote:
>In comp.lang.javascript message <S+Zj6ZDP...@J.A830F0FF37FB96852AD0
>8924D9443D28E23ED5CD>, Sun, 18 Oct 2009 15:08:15, John G Harris
><jo...@nospam.demon.co.uk> posted:

<snip>


>> Decide exactly what
>>the problem is. Now review the following sentence in your web page :
>>
>>"Then every statement will be terminated by a semicolon."
>
>But I was writing about valid JavaScript, not JavaScript with a syntax
>error.

<snip>

I don't know what "every" means in Physics, but in Mathematics and
Computer Science it means every, all, without as many as one exception.

You say that by inserting semicolons you can make every statement end
with a semicolon. I have demonstrated that there is a case where by
adding a semicolon at the end of a statement you get a syntax error.
Therefore it is not true that "every statement will be terminated by a
semicolon."

The mess would be avoided if your paragraph started with something like
"Each statement ends with either a semicolon, a close curly bracket, or
a nested, smaller, statement."

Then you can say what you want about semicolon-terminated statements
without causing VK-like confusion.

John

PS Students who demanded to be told the answer made me very irritable.
--
John Harris

Branco

unread,
Oct 19, 2009, 4:08:59 PM10/19/09
to
vaib wrote:
<snip>
> I am relatively new to JavaScript and I have to develop something that
> seems like a good amount o learning curve for me right now.
>
> To make it simple here's the most simplistic view of what I have to do
> - A page where two DIVs are placed side by side and there's a button

> below. On the click of the button the DIVs should exchange their
> positions ( ofcourse, with everything in them also being exchanged ).
> I have to make it resolution free.
>
> I do not need any code as such ( although any help is appreciated )
> but what approach to take would be a great help.
<snip>

If all you want is to exchange their positions, then I'd suggest you
make the positioning a css rule and simply apply the correct style to
each div.

<!--Start Air Code -->
<style>
.left-box {float:left;}
.right-box {float:right}
#A { /*...*/ }
#B { /*...*/ }
</style>
<script>
function ReplaceClass(E, OldClass, NewClass){
//replaces OldClass for NewClass in E.className.
//returns true if successfull, false otherwise
//...
}

function Swap(A, B) {
A = document.getElementById(A);
B = document.getElementById(B);

if (ReplaceClass(A, 'left-box', 'right-box')) {
ReplaceClass(B, 'right-box', 'left-box');
} else {
ReplaceClass(B, 'left-box', 'right-box');
ReplaceClass(A, 'right-box', 'left-box');
}
} //function Swap(...)
</script>
<div id='A' class='left-box'><div>Text in A</div></div>
<div id='B' class='right-box'><div>Text in B</div></div>
<input type='button' value = 'Swap' onclick='Swap()'/>
<!--End Air Code -->

Otherwise, if you want to actually exchange the content of each div,
then notice that styles based on parentship will be affected. Also,
sh*te may ensue if you try to swap two elements where one is contained
in the other.

<!--Start Air Code -->
<style>
#A div {font-weight:bold;font-size:14px;}
#B div {font-size:32px;color:red}
</style>
<script>
function Swap(A, B) {
//swaps the content of two elements
A = document.getElementById(A);
B = document.getElementById(B);
var Temp = document.createElement("div");
var c = A.childNodes;
while(c.length > 0) Temp.appendChild(c[0]);
c = B.childNodes;
while(c.length > 0) A.appendChild(c[0]);
c = Temp.childNodes;
while(c.length > 0) B.appendChild(c[0]);
Temp = null;
}
</script>
<div id='A' class='left-box'><div>Text in A</div></div>
<div id='B' class='right-box'><div>Text in B</div></div>
<input type='button' value = 'Swap' onclick='Swap()'/>
<!--End Air Code -->

HTH.

Regards,

Branco.

kangax

unread,
Oct 20, 2009, 2:48:45 AM10/20/09
to
Thomas 'PointedEars' Lahn wrote:
> VK wrote:

[...]

>> {"key1":"value1"}
>> structure is a valid JSON object data but it is not JavaScript syntax
>> compatible for the above spelled reasons and leads to "invalid label"
>> syntax error.

[...]

Interesting. I've never seen array literal being used for this.

It just occurred to me that one could also use a comma operator instead
of so-common grouping one:

var json = '{ "x": 1 }';
eval('1,' + json);

which would actually result in concatenation of only 2 strings instead
of 3, and be arguably cleaner (at least 3 characters shorter) -

var json = '{ "x": 1 }';
eval('(' + json + ')');

However, grouping operator is probably more efficient here, since it
merely evaluates an expression (avoiding even GetValue), whereas comma
operator would result in evaluation of first expression, followed by
calling GetValue on it, and so on with the second one.

This is all just a minor quibble, of course.

[...]

--
kangax

Thomas 'PointedEars' Lahn

unread,
Oct 20, 2009, 3:40:17 AM10/20/09
to
kangax wrote:

> It just occurred to me that one could also use a comma operator instead
> of so-common grouping one:
>
> var json = '{ "x": 1 }';
> eval('1,' + json);
>
> which would actually result in concatenation of only 2 strings instead
> of 3, and be arguably cleaner (at least 3 characters shorter) -
>
> var json = '{ "x": 1 }';
> eval('(' + json + ')');
>
> However, grouping operator is probably more efficient here, since it
> merely evaluates an expression (avoiding even GetValue), whereas comma
> operator would result in evaluation of first expression, followed by
> calling GetValue on it, and so on with the second one.
>
> This is all just a minor quibble, of course.

ACK. However, I would appreciate it if you quoted me so that the meaning of
my replies cannot be misinterpreted. Your current quoting suggests that VK
would have been right, and that I proposed a workaround for a perceived
incompatibility problem, which I definitely did _not_.

wilq

unread,
Oct 20, 2009, 4:33:31 AM10/20/09
to
> Luuk wrote:
> > vaib schreef:
> >http://w3schools.com/js/default.aspis a nice starting point...
>
> It isn't.
>

What a constructive criticism.

Thomas 'PointedEars' Lahn

unread,
Oct 20, 2009, 4:39:47 AM10/20/09
to
wilq wrote:

As is yours, isn't it?

I won't start the whole discussion again just because you are too lazy for a
bit of research. There are enough examples available in the newsgroup's
archives where w3schools.com is so utterly wrong that its misinformation is
the cause of the problem, to discount it as a viable development resource.

You would have know that had you read my posting whole.


PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16

Richard Cornford

unread,
Oct 20, 2009, 4:53:31 AM10/20/09
to

Why would anyone expect/want criticism to be constructive? The
validity/veracity of criticism is not modified by how
constructive/destructive it may be perceived as being.

What is absent from the above is informative criticism. A statement is
made but it is not justified, which leaves it hanging on the reader's
opinion of the individual making the statement.

Personally, I look at w4schools' javascript material and observe a
"test" in which a surprising proportion of the multiple choice answers
offered do not even include the correct answer (it is such a trivial
test that only one case would be surprising). That does not seem to bode
well for the quality of the rest of the material on the site, but still
doesn't represent a 'constructive' criticism.

Richard.

kangax

unread,
Oct 20, 2009, 11:21:20 AM10/20/09
to
Thomas 'PointedEars' Lahn wrote:
> kangax wrote:
>
>> It just occurred to me that one could also use a comma operator instead
>> of so-common grouping one:
>>
>> var json = '{ "x": 1 }';
>> eval('1,' + json);
>>
>> which would actually result in concatenation of only 2 strings instead
>> of 3, and be arguably cleaner (at least 3 characters shorter) -
>>
>> var json = '{ "x": 1 }';
>> eval('(' + json + ')');
>>
>> However, grouping operator is probably more efficient here, since it
>> merely evaluates an expression (avoiding even GetValue), whereas comma
>> operator would result in evaluation of first expression, followed by
>> calling GetValue on it, and so on with the second one.
>>
>> This is all just a minor quibble, of course.
>
> ACK. However, I would appreciate it if you quoted me so that the meaning of
> my replies cannot be misinterpreted. Your current quoting suggests that VK
> would have been right, and that I proposed a workaround for a perceived
> incompatibility problem, which I definitely did _not_.

Sorry about that. Apparently, I didn't pay enough attention when quoting.

--
kangax

vaib

unread,
Oct 20, 2009, 3:22:22 PM10/20/09
to
> kangax- Hide quoted text -
>
> - Show quoted text -

Thanks all you. I got the solution ( and understood it too ;) ).
I'll post one more problem I am facing - it's a code that I wrote. It
needs some advise.

Thanks to all.


- Vaibhav

0 new messages