Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 14 of 14
  1. #1
    New Coder
    Join Date
    Mar 2010
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts

    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>

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,471
    Thanks
    0
    Thanked 634 Times in 624 Posts
    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/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #3
    Regular Coder Taro's Avatar
    Join Date
    Oct 2011
    Location
    Geraldton, Ontario
    Posts
    155
    Thanks
    1
    Thanked 1 Time in 1 Post
    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,

    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.

  • #4
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    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

  • #5
    New Coder
    Join Date
    Mar 2010
    Posts
    16
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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??

  • #6
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,471
    Thanks
    0
    Thanked 634 Times in 624 Posts
    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/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #7
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    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".
    Last edited by Krupski; 06-08-2012 at 02:34 PM.
    "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

  • #8
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,471
    Thanks
    0
    Thanked 634 Times in 624 Posts
    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/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #9
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    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

  • #10
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,471
    Thanks
    0
    Thanked 634 Times in 624 Posts
    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.
    Last edited by felgall; 06-09-2012 at 12:42 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #11
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    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
    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

  • #12
    Regular Coder Krupski's Avatar
    Join Date
    Dec 2010
    Location
    United States of America
    Posts
    505
    Thanks
    39
    Thanked 47 Times in 46 Posts
    @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

  • #13
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,471
    Thanks
    0
    Thanked 634 Times in 624 Posts
    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.
    Last edited by felgall; 06-09-2012 at 04:22 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #14
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,471
    Thanks
    0
    Thanked 634 Times in 624 Posts
    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/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •