How does the following script work?

O

opt_inf_env

Hello,

I try to understand how the following script works.

<style type="text/css">
.fauxLink {text-decoration: underline;
color: blue;
cursor: pointer;
font-weight: bold;
}
</style>
<script type="text/javascript">
function showHide(ele){
var x;
if ( document.getElementById && (x =
document.getElementById(ele)) && x.style )
{
x.style.display = ('none' == x.style.display)?
'' : 'none' ;
}
}
</script>
<span class="fauxLink" onclick="showHide('tgt'); ">Click me</span>
<span id="tgt">&nbsp;<br>I am some text</span>

The main problems are:
1. I do not know what "getElementById" do. And I cannot to find
information about than in Internet.
2. What do this line "x.style.display = ('none' ==
x.style.display)? '' : 'none' ;".
 
D

David Dorward

V

VK

1. I do not know what "getElementById" do. And I cannot to find
information about than in Internet.

getElementById(idString) Gets an Element By its ID (idString)

To find it out you may go to Google, type in "getElementById method"
and press "I'm feeling lucky".

So if in your HTML page you have an element like <div id="myDiv"> then
document.getElementById('myDiv') will return a reference to this
element.

2. What do this line "x.style.display = ('none' ==
x.style.display)? '' : 'none' ;".

I'm not sure how is it called in the books, I used to call it "If
Shortcut". So instead if writing:
if (someConditionIsTrue) {
x = variant1;
}
else {
x = variant2;
}

you write:
x = (someConditionIsTrue) ? variant1 : variant2;

It's very convenient for your fingers for simple assingments (but
doesn't affect anyhow on the code performance).

The sample you demonstrated is a bit odd from the common programming
practice, because normally (this is what I suggest to you) the
comparing element always goes to the left, and the comparison template
goes to the right. So it should be:

x.style.display = (x.style.display=='none')? '' : 'none';

which equals to:
if (x.style.display == 'none') {
x.style.display == '';
}
else {
x.style.display == 'none';
}

which is now (in any shall perform form) is a proper JavaScript code,
but wrong from the DOM side; because we have two 'display' property,
and empty string is not one of them: "none" and "block";

So bringing your 2nd sample to the conventional form we have:

x.style.display = (x.style.display == 'none')? 'block' : 'none';
 
L

Lasse Reichstein Nielsen

VK said:
I'm not sure how is it called in the books, I used to call it "If
Shortcut".

Other names are "conditional expression", "questionmark-colon
operator" or (misguidedly) "the ternary operator". (The third is only
identifying because ?: is the *only* ternary operator in the
language. A ternary operator is an operator that takes three
arguments, whereas * is a binary operator)).
So instead if writing: ....
you write:
x = (someConditionIsTrue) ? variant1 : variant2;

Exactly.

Another way to look at it is syntactically. In most programming
languages there are (at least) two syntactic categories: Expressions
and statements. An expression is evaluted to a value, and a statement
is executed to have an effect. Examples of expressions are, e.g., "42"
and "x+y". Examples of statements are, e.g.,"x=42;" and "while(true){}".

Since we want programs to be useful, we need a way to not always
execute exactly the same code. For that we use conditional brances.
The typical branch is the "if" statement:
if (conditionExpression) {
conditionalStatements1;
} else {
conditionalStatements1;
}

This is itself a statement. Depending on the value of the condition
expression, it has the same behavior as on of the conditioned
statements. It is not decided until runtime which one it is.

So, we have the syntactic category of statements, and we want to make
a choice at runtime about which choice of statement we want to
execute. The entire compund of this switching logic and both
statements is itself a statement.

Now generalize this to any other syntactic category, e.g.,
expressions. We want something that, depending on a condition
expression, behaves as one of two expressions. Therefore it must
itself be an expression. The parts of this expression will be
the condition expression and two other expressions. Not wanting
to waste more keywords, the solution chosen in C and inherited in
many later languages is:
conditionExpression ? conditinoalExpression1 : conditionalExpression2

It works for expressions just as "if" does for statements (except that
expressions must have a value, so you can't omit the "else" branch,
where the empty statement is a valid default for the "if" statement).
It's very convenient for your fingers for simple assingments (but
doesn't affect anyhow on the code performance).

True. It affects readability. Long, convoluted conditions should
probably not be put into one expression, whereas short, simple
ones should not be expanded into a multiline "if". But there are
no hard rules.
The sample you demonstrated is a bit odd from the common programming
practice, because normally (this is what I suggest to you) the
comparing element always goes to the left, and the comparison template
goes to the right. So it should be:

x.style.display = (x.style.display=='none')? '' : 'none';

Religious wars have been started over less :)

There is a school that encourages that it be written
'none' == x.style.display
because it prevents accidentally leaving out one of the "="'s and
still having a valid expression (an assignment even, debugging it is
*so* fun).

I'm not of that school, and I find much easier to read it the way you
suggest, but then again, I usually use Java where only boolean
expressions are allowed as condition expressions. In C and Javascript,
it's much easier to have the bug go undetected.

if (x.style.display == 'none') {
x.style.display == '';
} ....
which is now (in any shall perform form) is a proper JavaScript code,
but wrong from the DOM side; because we have two 'display' property,
and empty string is not one of them: "none" and "block";

Actually, there are plenty of valid values for the display property
("none","block","inline","table-row","table-cell", ...).
So bringing your 2nd sample to the conventional form we have:

x.style.display = (x.style.display == 'none')? 'block' : 'none';

This would fail if "x" refers to a table row, where "block" is not a
valid display type - except in IE, where it is the only one that
works. To avoid the problem of deciding whether you are running in
a mondern browser or in IE, assigning the empty string does just
what you want.

Setting a property of a style object to the empty string is generally
implemented as equivalent to doing style.removeProperty("propertyName").
This is consistent with the W3C DOM 2 Style CSS specification, which
says that reading the value of an unassigned property gives the empty
string.

Removing the property is exactly what is wanted in this case, as that
will make the default value be used, whether it is "block" or
"table-row".

/L
 
R

RobG

VK wrote:
[...]
2. What do this line "x.style.display = ('none' ==
x.style.display)? '' : 'none' ;".
[...]
The sample you demonstrated is a bit odd from the common programming
practice, because normally (this is what I suggest to you) the
comparing element always goes to the left, and the comparison template
goes to the right. So it should be:

x.style.display = (x.style.display=='none')? '' : 'none';

The reason it was written the other way around is that sometimes
fingers get things muddled and instead of '==' they type '=', i.e.
instead of a comparison an assignment is typed.

If you type ('none' = x.style.display)... an error (should) result
and the script fails, forcing you to fix the error.

On the other hand, typing (x.style.display = 'none')... will always
evaluate to true and you will have to test thoroughly to find the
error then hunt around your code to fix it (though I believe some
older browsers will 'fix' the accidental assignment in some
circumstances).
which equals to:
if (x.style.display == 'none') {
x.style.display == '';
}
else {
x.style.display == 'none';
}

which is now (in any shall perform form) is a proper JavaScript code,
but wrong from the DOM side; because we have two 'display' property,
and empty string is not one of them: "none" and "block";

There are many possible values for the display attribute:

inline, block, list-item, run-in, compact, marker, table,
inline-table, table-row-group, table-header-group,
table-footer-group, table-row, table-column-group, table-column,
table-cell, table-caption, none, inherit.

<URL:http://www.w3.org/TR/REC-CSS2/visuren.html#display-prop>

It is best to toggle between 'none' and '' because that will let the
browser return to the default for the element, which may be any of
the above.
So bringing your 2nd sample to the conventional form we have:

x.style.display = (x.style.display == 'none')? 'block' : 'none';

It should stay as originally presented:

x.style.display = ('none' == x.style.display )? '' : 'none';
 
L

Lasse Reichstein Nielsen

RobG said:
On the other hand, typing (x.style.display = 'none')... will always
evaluate to true and you will have to test thoroughly to find the
error then hunt around your code to fix it (though I believe some
older browsers will 'fix' the accidental assignment in some
circumstances).

Those "older browsers" include all Gecko based browsers, if the code
appears in a script element set to JavaScript 1.2, e.g. :

<script language="JavaScript1.2">
// ...
if (x.style.display = 'none')
// ...
</script>

The semantics of Javascript 1.2 (the most recent one only between
Netscape 4.0 an 4.05) mandate this behavior, and Netscape browsers
and Gecko based browsers actually implement JavaScript 1.2 semantics
on demand.

The code will of course fail the first time it hits an IE or Opera
browser, which only implement ECMAScript semantics.

Never, *never*, use the language attribute! Never!

/L 'Never!'
 
V

VK

2. What do this line "x.style.display = ('none' ==
I'm not sure how is it called in the books, I used to call it "If Shortcut".
Other names are "conditional expression", "questionmark-colon
operator" or (misguidedly) "the ternary operator".

Ternary operator - that's the word! While working on VBA programming I
used to use it. It just was a bit to weird to hold in your memory
longer as it's needed.
 
L

Lasse Reichstein Nielsen

VK said:
Ternary operator - that's the word! While working on VBA programming I
used to use it. It just was a bit to weird to hold in your memory
longer as it's needed.

The naming confusion dates back to the C language, where the notation
was introduced. In the Kernighan and Ritchie "The C Programming
Language" book (I only have the 2nd edition), the index entry is "?:
conditional expression", and the specification of it is an a section
called "Conditional Operator".

However, where the operator is first introduced, a sentence goes: "The
/conditinoal expression/, written with the ternary operator "?:",
....". I've had students reading that as "ternary operator" being the
name of the operator (quite a lot of them, even), and I can see that
it is a widespread reading :).

/L
 
V

VK

x.style.display = (x.style.display=='none')? '' : 'none';
Religious wars have been started over less :)
There is a school that encourages that it be written
'none' == x.style.display

Not really a new religious war, just a dispute of how to read the
Fathers of the Chearch :)

The left-to-right order coming from the books of ALGOL was not some
up-from-the-air decision. It reflects the human phisical specific where
the left brains hemisphere (controlling the *right* part of our
body/world) is dominant in 96% of cases. It also reflected in our
mentality and language. In all Indo-European languages (including
modern English) *the right* (as opposed to left) is of the same root as
*the right* (as opposed to wrong). So it was a natural decision to
place something of a "questionnable quality" to the left, and the
"sample of the quality" to the right:
if (something == template)
As well it was natural decision to place something that "should become"
on the left and "someting what already became" to the left:
var c = a + b;

So I consider the school you've just mentioned as a deviation of the
Learning. :))
 

Ask a Question

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

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

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top