473,320 Members | 1,867 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

How does the following script work?

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' ;".

Jul 23 '05 #1
8 1471
op*********@yahoo.com wrote:
1. I do not know what "getElementById" do. And I cannot to find
information about than in Internet.
It does exactly what it says on the tin - it gets an element by its id.
http://www.w3.org/TR/2000/REC-DOM-Le...ml#ID-getElBId
2. What do this line "x.style.display = ('none' ==
x.style.display)? '' : 'none' ;".


Means the same as:

if ('none' == x.style.display) {
x.style.display = '';
} else {
x.style.display = 'none';
}

--
David Dorward <http://blog.dorward.me.uk/> <http://dorward.me.uk/>
Home is where the ~/.bashrc is
Jul 23 '05 #2
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';

Jul 23 '05 #3
"VK" <sc**********@yahoo.com> writes:
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".


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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #4
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';

--
Rob
Jul 23 '05 #5
RobG <rg***@iinet.net.auau> writes:
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!'
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #6
VK
>> 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".

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.

Jul 23 '05 #7
"VK" <sc**********@yahoo.com> writes:
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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #8
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. :-))

Jul 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: jasonbrown1999 | last post by:
Someone told me the following script could be used to run harmful commands on the server, by passing commands into the script. What the script does is encode an affiliate URL, create two frames,...
3
by: Ed Brandmark | last post by:
I have a tag of the form <SCRIPT LANGUAGE="JavaScript1.1" SRC="foo.js"..... and was wondering if this delays the loading of my page until that file foo.js downloads. It seems that if I place...
11
by: Saqib Ali | last post by:
Please excuse me, this is a fairly involved question that will likely require you to save the file below to a file and open it in a browser. I use Mozilla 1.5, so the problem I describe below...
3
by: Steve Richter | last post by:
How does the following javascript work? After the first script runs the variables "sGeobytesCity", "sGeobytesRegion" and "sGeobytesCountry" contain values that have been set somehow by the...
12
by: DEN | last post by:
Hello, I need to remove toolbar and menubar from my current window (not opened with window.open, it would be too easy!!!). I've tried to use the window.toolbar.visible=false property, but it has...
3
by: paul | last post by:
HI! I have being to add the following as part of a function but it just will not work as is but I don't know why, can someone point out why. This opens up a popup window for a popup detection...
2
by: Robert S | last post by:
I am trying to get the output of a php script to be displayed on a page using the following (I have drastically simplified the PHP script and have used MSXML2.XMLHTTP.4.0): time.html: <html>...
5
by: Cylix | last post by:
this.menus = { root: new Array };
2
by: Greg Scharlemann | last post by:
The last time I tried to ask this question...Google Groups screwed up my message and there was no subject (sorry for that - I know it's annoying). I'm trying to learn how to develop a plug-in...
1
by: Iain | last post by:
I have the following .net page with a pushbutton in a datagrid. This pushbutton should delete the selected record. It works in the same manner in many other pages of the same format (I actually...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.