Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 06-07-2012, 02:25 AM   PM User | #1
locbtran
New Coder

 
Join Date: Mar 2010
Posts: 16
Thanks: 0
Thanked 0 Times in 0 Posts
locbtran is an unknown quantity at this point
Single vs Double Quotes (Very Confusing!!)

The row in the table would highlight whenever I mouse over it.
This works perfectly in HTML but I would like to convert from HTML code to Javascritp code to make it more dynamic.
Code:
<html>
<body>

<TABLE border=1>
 <TR bgcolor="#FFFFFF" onMouseOver="this.bgColor='gold';" onMouseOut="this.bgColor='#FFFFFF';">
   <TD>Mauritania</td><TD>21N</TD><TD>24N</TD><TD>&nbsp;</TD><TD>&nbsp;</TD>
 </TR>
 <TR bgcolor="#FFFFFF" onMouseOver="this.bgColor='gold';" onMouseOut="this.bgColor='#FFFFFF';">
   <TD>Myanmar</td><TD>&nbsp;</TD><TD>M TBA</TD><TD>M TBA</TD><TD>&nbsp;</TD>
 </TR>
 <TR bgcolor="#FFFFFF" onMouseOver="this.bgColor='gold';" onMouseOut="this.bgColor='#FFFFFF';">
   <TD>Nepal</td><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>M TBA</TD>
 </TR>
</TABLE>
 
</body>
</html>


I tried to convert it to Javascript but it only gives me a blank screen.
This is very frustrating because I don't know where I'm going wrong.
Any comments of suggestions would be greatly appreciated.

Code:
<html>
<head>
<script type="text/javascript">

function init(){
   document.writeln('<TABLE border=1>');

   document.writeln('<TR bgcolor="#FFFFFF" onMouseOver="this.bgColor='gold';" onMouseOut="this.bgColor='#FFFFFF';">');
   document.writeln('<TD>Mauritania</td><TD>21N</TD><TD>24N</TD><TD>&nbsp;</TD><TD>&nbsp;</TD> </TR>');

   document.writeln('<TR bgcolor="#FFFFFF" onMouseOver="this.bgColor='gold';" onMouseOut="this.bgColor='#FFFFFF';">');
   document.writeln('<TD>Myanmar</td><TD>&nbsp;</TD><TD>M TBA</TD><TD>M TBA</TD><TD>&nbsp;</TD></TR>');

   document.writeln('<TR bgcolor="#FFFFFF" onMouseOver="this.bgColor='gold';" onMouseOut="this.bgColor='#FFFFFF';">');
   document.writeln('<TD>Nepal</td><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>M TBA</TD></TR></TABLE>')';
}
</script>
</head>

<body onload="init()">
</body>
</html>
__________________
HotDeals
locbtran is offline   Reply With Quote
Old 06-07-2012, 03:01 AM   PM User | #2
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,447
Thanks: 0
Thanked 496 Times in 488 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Your content contains both ' and " so if you wrap the whole thing inside ' you need to escape the inner ' as \'

document.writeln used to be JavaScript back in the Netscape 2 days but is now as dead as Netscape 4 is.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
felgall is offline   Reply With Quote
Old 06-07-2012, 04:06 AM   PM User | #3
Taro
Regular Coder

 
Taro's Avatar
 
Join Date: Oct 2011
Location: Geraldton, Ontario
Posts: 155
Thanks: 1
Thanked 1 Time in 1 Post
Taro is an unknown quantity at this point
Sometimes it may matter in terms of how you use JavaScript, or how easy you want to have it read.

Check this thread.

As Old Pedant said,

Quote:
No to JavaScript, assuming they are correctly matched up.
You may have to just rewrite the code and not convert it; some people use double quotes for HTML and single quotes for JavaScript.

Hope this helps.
__________________
Element ID

Webs Support Helper

Your friendly neighborhood Taroman.
Taro is offline   Reply With Quote
Old 06-07-2012, 07:05 AM   PM User | #4
Krupski
Regular Coder

 
Krupski's Avatar
 
Join Date: Dec 2010
Location: United States of America
Posts: 502
Thanks: 39
Thanked 47 Times in 46 Posts
Krupski is on a distinguished road
Quote:
Originally Posted by locbtran View Post
I tried to convert it to Javascript but it only gives me a blank screen.
This is very frustrating because I don't know where I'm going wrong.
Any comments of suggestions would be greatly appreciated.
The replies you received, although correct, are not very informative as to explaining the actual problem.

In Javascript, you can use single or double quotes, no problem.

But consider this line:

var string = 'I hope it's not too late to begin';

It looks fine, but it's a syntax error. The single quote after the "t" in "it's" will be considered by Javascript as the end of the line. So, Javascript sees this line as:

var string = 'I hope it'(syntax error)

To make it work, you need to "escape" the "bad" character - that is, you have to tell Javascript "I mean this to be an apostrophe, not the end of the line!".

You do this with a backslash character. So, the above line, corrected, would be:

var string = 'I hope it\'s not too late to begin';

In fact, every single quote that isn't meant to be the end of line must be escaped. Consider this line of code where the URL of the image is generated by some other function:

var picture = '<img src="getImage('background')" alt="image">';

The single quotes around the word "background" will confuse Javascript and is a syntax error.

The correct code is:

var picture = '<img src="getImage(\'background\')" alt="image">';

I hope this helps you understand the concept........


P.S. don't use "document.write"... it will give you no end of grief and trouble.
__________________
"Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov
Krupski is offline   Reply With Quote
Old 06-08-2012, 03:24 AM   PM User | #5
locbtran
New Coder

 
Join Date: Mar 2010
Posts: 16
Thanks: 0
Thanked 0 Times in 0 Posts
locbtran is an unknown quantity at this point
Quote:
Originally Posted by Krupski View Post
]
I hope this helps you understand the concept........

P.S. don't use "document.write"... it will give you no end of grief and trouble.
Thanks for the info, it was very helpful.

instead of "document.write", should I be using innerHTML with getElementByID??
__________________
HotDeals
locbtran is offline   Reply With Quote
Old 06-08-2012, 07:37 AM   PM User | #6
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,447
Thanks: 0
Thanked 496 Times in 488 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by locbtran View Post
instead of "document.write", should I be using innerHTML with getElementByID??
That's the simplest solution for beginners - innerHTML has fewer issues than document.write does and is just as easy to use.

The way that avoids all the issues is to use the proper DOM commands that make up about 60% of JavaScript.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
felgall is offline   Reply With Quote
Old 06-08-2012, 02:22 PM   PM User | #7
Krupski
Regular Coder

 
Krupski's Avatar
 
Join Date: Dec 2010
Location: United States of America
Posts: 502
Thanks: 39
Thanked 47 Times in 46 Posts
Krupski is on a distinguished road
Quote:
Originally Posted by locbtran View Post
Thanks for the info, it was very helpful.

instead of "document.write", should I be using innerHTML with getElementByID??
Yes, you can use "document.getElementById('id')" then set the innerHTML of the element.

You can also get the element and do an "appendChild" or "replaceChild". In that case, you use "document.createElement" and then insert it into the DOM.

Picture this:

<p>
<span id="replaceme"></span>
</p>


Code:
    var e = document.getElementById('replaceme');
    var s = document.createElement('span');
    s.innerHTML = 'I am the new element';
    e.parentNode.appendChild(s); // this is "append"
    e.parentNode.replaceChild(s, e); // this is "replace"
If you get the parent element of the span (the <p>), then create a new element, then do an "appendChild", you end up with this:

<p>
<span id="replaceme"></span>
<span>I am the new element</span>
</p>



If you do a "replaceChild" instead, you get this:

<p>
<span>I am the new element</span>
</p>


Notice that I used s.innerHTML = in the demo code. The correct way to do it would have been to create a new text node and append it to the span, but all this is confusing enough without making it worse!

NOTE! The code to append or replace a node has to come AFTER the HTML itself. That is, the span called "replaceme" MUST EXIST before the Javascript tries to access it, else it will fail.

To be sure it works, either place the JS AFTER the HTML or (better) use a "window.onload" event to trigger the JS after all the page is finished loading.

If that's confusing, then forget about it for now and just use "innerHTML".
__________________
"Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov

Last edited by Krupski; 06-08-2012 at 02:34 PM..
Krupski is offline   Reply With Quote
Old 06-08-2012, 09:05 PM   PM User | #8
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,447
Thanks: 0
Thanked 496 Times in 488 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by Krupski View Post
YTo be sure it works, either place the JS AFTER the HTML or (better) use a "window.onload" event to trigger the JS after all the page is finished loading.
You have that backwards.

The BEST place to put the JavaScript is immediately before the </body> tag. Using onload properly is even more convoluted than the DOM processing that you have been demonstrating and by placing the JavaScript after the content of the page you will almost never need to use onload.

If you do need to use onload you should code it like this (so it doesn't clash with any onloads added by other scripts)::

Code:
(function() {
if (window.addEventListener)
addEvent = function(ob, type, fn ) {
**ob.addEventListener(type, fn, false );
};
else if (document.attachEvent)
addEvent = function(ob, type, fn ) {
  var eProp = type + fn;
  ob['e'+eProp] = fn;
  ob[eProp] = function(){ob['e'+eProp]( window.event );};
  ob.attachEvent( 'on'+type, ob[eProp]);
};
*
addEvent(window. 'load', nameOfFunctionToRunOnLoad);
})();
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
felgall is offline   Reply With Quote
Old 06-09-2012, 12:12 AM   PM User | #9
Krupski
Regular Coder

 
Krupski's Avatar
 
Join Date: Dec 2010
Location: United States of America
Posts: 502
Thanks: 39
Thanked 47 Times in 46 Posts
Krupski is on a distinguished road
Quote:
Originally Posted by felgall View Post
You have that backwards.
The BEST place to put the JavaScript is immediately before the </body> tag. Using onload properly is even more convoluted than the DOM processing that you have been demonstrating and by placing the JavaScript after the content of the page you will almost never need to use onload.
I know that JS code usually goes "near the top" but I wanted to point out the common trap of trying to reference an object before it exists.

As far as using onload, I have a VERY simple little piece of code that I use to run any function I wish "onload" without having to re-write event handlers etc...

I can't take credit for it though... it was originally written by a guy whose screen name is "PentaPenguin"......

Code:
    /**
    * window.onload handler - (original code by pentapenguin)
    **/
    var onload_functions = [];
    window.onload = function() {
        var len = onload_functions.length;
        while (len--) {
            eval(onload_functions[len]);
        };
    };
Stick this in right at the top of the page (before any other JS).

Then say you want to run a function named "screenInit()" after the page loads. Simply place this line ANYWHERE:

Code:
    onload_functions.push('screenInit()');
...and it works. No fuss, no muss!

(do I hear screams? NO!!!!! EVAL!!!! BAD!!!!!!!)
__________________
"Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov
Krupski is offline   Reply With Quote
Old 06-09-2012, 12:27 AM   PM User | #10
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,447
Thanks: 0
Thanked 496 Times in 488 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by Krupski View Post
I know that JS code usually goes "near the top"
No it doesn't - for the last five years or so all the JavaScript experts have been recommending that JavaScript be attached at the BOTTOM so that all the HTML the script references will already exist before the script is run.

Only those who learnt JavaScript over five years ago and haven't kept up to date and those who have learnt JavaScript history instead of learning how to write modern JavaScript still attach their scripts at the top where they then have to include lots more code to make it delay running until after the rest of the page loads.

Quote:
Originally Posted by Krupski View Post
eval(onload_functions[len]);
That's about the worst thing you can do - in properly written JavaScript the situations where you need to use the evil eval command are extremely rare. There is almost always a better way to write the code that doesn't rely on that statement (which should never have been added to JavaScript in the first place).

In the past ten years I have come across exactly one situation where I haven't been able to find an alternative to using eval and that is where you add a method to the Function object that rewrites functions by converting them to text, changing them and then eval() them back into a function. Where you are not trying to get JavaScript to actually rewrite itself there is no need for eval().

In your particular case the eval version is actually longer than the version without eval - you should substitute the following if you insist on using that antiquated approach:

Code:
onload_functions[len]();
That will work fine once you fix the way you load the array:

Code:
onload_functions.push(screenInit);
That PentaPenguin must not have known JavaScript all that well to want to keep converting functions into strings unnecessarily.

Anyway, your version still requires that a separate script be added to process the onloads for all the scripts in the page - my version doesn't require an extra script to do it. Your code is the way that it used to be done between about 2003 and 2006 from when browsers first allowed that code to run until the more flexible alternative of simply placing the scripts at the bottom of the page became the accepted way to write JavaScript.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 06-09-2012 at 12:42 AM..
felgall is offline   Reply With Quote
Old 06-09-2012, 01:29 AM   PM User | #11
Krupski
Regular Coder

 
Krupski's Avatar
 
Join Date: Dec 2010
Location: United States of America
Posts: 502
Thanks: 39
Thanked 47 Times in 46 Posts
Krupski is on a distinguished road
Quote:
Originally Posted by felgall View Post
No it doesn't - for the last five years or so all the JavaScript experts have been recommending that JavaScript be attached at the BOTTOM so that all the HTML the script references will already exist before the script is run.
I mis-read your post. You said
Quote:
The BEST place to put the JavaScript is immediately before the </body> tag.
I missed the slash. I thought you meant <body>, not </body>. My bad.
__________________
"Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov
Krupski is offline   Reply With Quote
Old 06-09-2012, 02:35 AM   PM User | #12
Krupski
Regular Coder

 
Krupski's Avatar
 
Join Date: Dec 2010
Location: United States of America
Posts: 502
Thanks: 39
Thanked 47 Times in 46 Posts
Krupski is on a distinguished road
@felgall:

I searched for a better "onload" solution and found this:

Code:
    /***
    * onload code handler
    * http://simonwillison.net/2004/may/26/addloadevent
    **/
    function addLoadEvent(func) {
        var onload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                if (onload) {
                    onload();
                }
                func();
            }
        }
    };
All it requires to send it functions to run is:

Code:
    addLoadEvent(function() {
        /* any JS code here */
    });
I tried it out and it works fine. Now let me ask you... is this the "right" way to do it, or is there yet a better way?

Thanks.

-- Roger
__________________
"Anything that is complex is not useful and anything that is useful is simple. This has been my whole life's motto." -- Mikhail T. Kalashnikov
Krupski is offline   Reply With Quote
Old 06-09-2012, 04:19 AM   PM User | #13
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,447
Thanks: 0
Thanked 496 Times in 488 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by Krupski View Post
I tried it out and it works fine. Now let me ask you... is this the "right" way to do it, or is there yet a better way?
Yes there's a better way - the way I already provided that means you can specify the onload separately for each script and don't need any common code.

Simply add the following code to each script independently and just change nameOfFunctionToRunOnLoad to the function that script needs to run onload. Then you can have one or two hundred such scripts in your page without having to have any common code to handle onload.

Code:
(function() {
if (window.addEventListener)
addEvent = function(ob, type, fn ) {
  ob.addEventListener(type, fn, false );
};
else if (document.attachEvent)
addEvent = function(ob, type, fn ) {
  var eProp = type + fn;
  ob['e'+eProp] = fn;
  ob[eProp] = function(){ob['e'+eProp]( window.event );};
  ob.attachEvent( 'on'+type, ob[eProp]);
};

addEvent(window. 'load', nameOfFunctionToRunOnLoad);
})();
Of course I haven't come across a situation that really needed onload aat all since I started attaching scripts at the bottom of the page - then the only onload code you need is:

Code:


ps. you still haven't answered my question from earlier where you have three pages where one page uses two scripts and two other pages use one of the scripts each as to where in those scripts you'd put your onload code - with my solution you put the onload code each script requires in that individual script.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/

Last edited by felgall; 06-09-2012 at 04:22 AM..
felgall is offline   Reply With Quote
Old 06-09-2012, 04:31 AM   PM User | #14
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,447
Thanks: 0
Thanked 496 Times in 488 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Since you don't appear to understand my point consider the following examples (using alert statements to represent the code to be run onload):

script1.js
Code:
a = function() {alert('one');};
(function() {
if (window.addEventListener)
addEvent = function(ob, type, fn ) {
  ob.addEventListener(type, fn, false );
};
else if (document.attachEvent)
addEvent = function(ob, type, fn ) {
  var eProp = type + fn;
  ob['e'+eProp] = fn;
  ob[eProp] = function(){ob['e'+eProp]( window.event );};
  ob.attachEvent( 'on'+type, ob[eProp]);
};

addEvent(window. 'load', a);
})();
script2.js
Code:
b = function() {alert('two');};
(function() {
if (window.addEventListener)
addEvent = function(ob, type, fn ) {
  ob.addEventListener(type, fn, false );
};
else if (document.attachEvent)
addEvent = function(ob, type, fn ) {
  var eProp = type + fn;
  ob['e'+eProp] = fn;
  ob[eProp] = function(){ob['e'+eProp]( window.event );};
  ob.attachEvent( 'on'+type, ob[eProp]);
};

addEvent(window. 'load', b);
})();
page one contains:
Code:
<script type="text/javascript" src="script1.js"></script>
page two contains:
Code:
<script type="text/javascript" src="script2.js"></script>
page three contains
Code:
<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>
Pages one and two will each display the one alert they are supposed to while page three will display both alerts.

Using this code there is no conflict needing to be resolved when you add or remove scripts from any page and also no extra common code required to handle conflicts that don't exist when you use the correct JavaScript event processing.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
felgall is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 05:05 AM.


Advertisement
Log in to turn off these ads.