Web Analytics Made Easy -
StatCounter JavaScript - Frequently Asked Questions - CodingForum

Announcement

Collapse
No announcement yet.

JavaScript - Frequently Asked Questions

Collapse
This topic is closed.
X
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • JavaScript - Frequently Asked Questions

    If you have input on the questions already in the FAQ or want to suggest a new question for someone to write an answer to, please post here.


    Index:
    1. How do I debug JavaScript as used on a webpage?
    2. How do you read, write, delete and detect support for cookies?
    3. What are the limits on cookies?
    4. What is Javascript good for?
    5. How do I format a number so that it always has two decimals?
    6. How do I trim whitespace from the beginning and end of a string?
    7. Why does parseInt('08') generate 0?
    8. How do I read/write files?
    9. How do I get multiple scripts to work on a single page?
    10. How do I convert a decimal number to hexadecimal, and the other way around?
    11. How do I add ordinals (st, nd, rd, th) to a number?
    12. How do I use JavaScript in external files?
    13. How can I use Javascript to protect my web pages?
    14. How do I shorten my lengthly if() statements?
    15. How do I hide my JavaScript source code?
    16. How do I use 'javascript:' links?


    Browsers:
    Last edited by liorean; Sep 28, 2005, 11:39 AM.
    liorean <[[email protected]]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #2
    Q: How do I debug JavaScript as used on a webpage?

    A: There are many approaches that you can take to debugging JavaScript. Let's discuss what you may do in the code itself first:
    • The most common is to insert alerts into the code, where you alert the values and types of variables, function arguments, and object properties. If you are doing code forking to support different ways of doing things, you may use confirms to force a certain path to be taken. If you want to be able to cut and paste the results, you may want to use prompts.
    • In an effort to get better error reporting you may use window.onerror or the try..catch statement. These may also be used to let code run without halting on errors, letting all errors be reported after the code has been executed.
    • Reduce hard-to-find errors that may sneak into your code by always following coding conventions such as explicitly ending statements by semicolon instead of relying on the semicolon insertion; by always using braces around the bodies of statements of the control structures (if, if..else, switch, while, do..while, for, for..in statements); by using parentheses instead of relying on operator precedence; by using consistent and verbose naming conventions; by using indentation and spacing consistently in a way that makes your source code easily readable; by avoiding automatic type casting through using explicit type casting or other methods to achieve the same effect; by using full syntaces where browsers allow shortcuts (this especially goes for ie), etc.
    • Run the code through js lint, which will do some work towards detecting potential coding errors.

    Ok, that was what you could do in the code itself. How about the detection of errors in the code?
    • Use many browsers for testing your scripts while you develop them. On windows, use at least ie6w, op7 and moz. On mac, use at least saf, op7, ie5m and moz. If things doesn't work in one or more of these browsers, see if you can do them differently. If not, make a fork for the chosen browser.
    • In ie, be sure to turn error reporting on. If you're on windows, use the Microsoft Script Debugger. You may use the debugger keyword inside the script to turn control of the execution of the script over to the debugger, if you need to track an error down. It's recommended that you use ie primarily for testing, and use op7 or moz for debugging.
    • In Op7, be sure to turn on JavaScript error reporting in the JavaScript Console. The Op7 JavaScript Console is far better than the ie bug reporting, and it contains a nice tracing feature that makes it easy to see where functions are called from. It also reports correct line number, in difference to iew.
    • In moz there's a sea of tools. You have the Mozilla JavaScript Console which reports errors and warnings as well as allows you to do simple script evaluation. You can turn on Strict Warnings to be alerted of many more potential problematic situations. You can use the DOM Inspector to view the document tree, the stylesheets tree, the computed styles, and JavaScript objects. You can use Venkman (the Mozilla JavaScript Debugger) to get a really advanced JavaScript debugger tool. You can use Ian Hickson's JavaScript Evaluation Sidebar or one of Jesse Ruderman's JavaScript Environment, view scripts bookmarklet, JavaScript Shell or view variables bookmarklet; or my ViewScripts bookmarklet.
    • In konq your are pretty much on your own. Use the source code tricks.
    • In saf you can turn on the hidden debug menu, to display frighteningly unhelpful error messages in the system Console, as well as get access to a more useful Show DOM Tree feature, if you turn on display of the Debug menu using the following command in the terminal while Safari is not running:
      Code:
      defaults write com.apple.Safari IncludeDebugMenu 1
    Last edited by liorean; Mar 26, 2004, 10:47 AM.
    liorean <[[email protected]]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

    Comment


    • #3
      Q: How do you read, write, delete and detect support for cookies?

      A: Let's take it one step at a time:
      • Reading cookies is simple. document.cookie is the JavaScript interface to cookies. It contains a semicolon separated list of cookies in the following fashion: "cookiename1=cookievalue1;...;cookienamen=cookievaluen". Only cookies for the current domain and path will be included in the string.
      • Writing cookies is more complicated. The easiest form of cookies are session-only cookies, which only lives as long as the browser window. These are written simply like this:
        Code:
        document.cookie="[i]cookiename[/i]=[i]cookievalue[/i]";
        Longer lived cookies are more advanced. They contain a string of the following pattern: "cookiename=cookievalue;expires=date;path=path;domain=domain;secure". Only include the path, domain and secure parts if you need to set them to something other than the default (which is '/', document.domain, and absent, respectively). date should be in the form of the return from the toUTCString method of instances of JavaScript's Date object.
      • Deleting cookies is done by overwriting a cookie, setting the expiry time in the past. Thus,
        Code:
        document.cookie='[i]cookiename[/i]=;'+
            'expires=Thu, 01-Jan-70 00:00:01 GMT;'+
            'path=[i]path[/i];'+
            'domain=[i]domain[/i]";
        where path and domain MUST be the same as they were when the cookie was originally set.
      • Detecting cookie support is done by writing a cookie and then reading it out again. If the value is the same as what you wrote, the browser supports cookies.

      If you don't feel like writing your own cookies handling script, there are many cookies libraries out there that you can use. I personally wrote two different ones in this thread, for instance, and the rest of the CF community has contributed to among other places this thread.
      Last edited by liorean; Mar 29, 2004, 01:50 PM.
      liorean <[[email protected]]>
      Articles: RegEx evolt wsabstract , Named Arguments
      Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
      Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

      Comment


      • #4
        Q: What are the limits on cookies?

        A: There's a list of limits put on cookies:
        • Cookies are limited to one domain. There is a limit of 20 cookies per domain. Cookies can be read only from pages from that domain.
        • Cookies can further be limited by paths, so that only pages with a specific path on that domain may read the cookie.
        • Cookies have an expiry date. If no such date is set, they will only survive as long as the browser session is still running.
        • Cookies that pass the expiry date are removed, but not necessarily from your harddrive. It depends on how your browser stores them.
        • Cookies may be 4kb long each, name of the cookie included.
        • Your max limit is no smaller than 300 cookies in total.
        • Most browsers allow no longer expiry time than three years. Some have a 90 day limit even.

        Official specifications exist for this, and can be found at Netscape Cookie Specification, which is the base for the IETF RFC2109 Specification.
        Last edited by liorean; Mar 1, 2004, 02:57 PM.
        liorean <[[email protected]]>
        Articles: RegEx evolt wsabstract , Named Arguments
        Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
        Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

        Comment


        • #5
          Q: What is Javascript good for?

          A: Because any general web user may have javascript in their browser disabled any use of javascript on a web page is best limited to enhancing the functionality, user friendliness and overall experience on your web pages. Nothing on your page should absolutely depend on javascript unless it's a non-essential part of the page. Javascript can also be used to make a page less friendly but there's no point in doing that.

          Useful things:
          Forms Validation, because Javascript can be disabled you must always perform validation on the server side but any validation of user input you can also perform interactively with the user before a form is submitted can save the user a round trip to the server and can save your server a hit where no actual transaction occurs.
          Interactive Forms, In the case of something like an online store it's always nice to update order totals and (when possible) shipping costs and other incidental costs (handling fees, taxes...) as the user updates the quantities or selects/deselects various items on the page. While you may want to post that toal back to your server for your own security, you must never trust that figure. Recalculate any totals based on the posted selections/quantities, you can however compare the posted total vs the server side computed total to detect bugs in the script and/or attempts at theft.
          Visual aides, the Title property can and should be used to give a user of your web page additional information about some element or group of elements on your page but javascript can be used to supplement the relatively weak content control available via the title property with a much richer full html content using a tooltip script.
          Check out the Forum Search. It's the short path to getting great results from this forum.

          Comment


          • #6
            Q: How do I format a number so that it always has two decimals?

            A: There are more than one way to do it. You could use the Number.prototype.toFixed method to do it, if it wasn't for the fact that ie5.5w is buggy and saf doesn't support it at all. Instead, do something like this:
            Code:
            Number.prototype.toDecimals=function(n){
                n=(isNaN(n))?
                    2:
                    n;
                var
                    nT=Math.pow(10,n);
                function pad(s){
                        s=s||'.';
                        return (s.length>n)?
                            s:
                            pad(s+'0');
                }
                return (isNaN(this))?
                    this:
                    (new String(
                        Math.round(this*nT)/nT
                    )).replace(/(\.\d*)?$/,pad);
            }
            This code extends all numbers to contain a toDecimals method, which you can invoke like this:
            Code:
            var
                nYourNumber=300.3,
                sYourFormattedNumber=nYourNumber.toDecimals(2); [color=green]// => '300.30'[/color]
            Last edited by liorean; Apr 2, 2004, 04:33 PM.
            liorean <[[email protected]]>
            Articles: RegEx evolt wsabstract , Named Arguments
            Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
            Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

            Comment


            • #7
              Q: How do I trim whitespace from the beginning and end of a string?

              A: By using regular expressions matching:
              Code:
              String.prototype.trim=function(){
                  return this.replace(/^\s*|\s*$/g,'');
              }
              
              String.prototype.ltrim=function(){
                  return this.replace(/^\s*/g,'');
              }
              
              String.prototype.rtrim=function(){
                  return this.replace(/\s*$/g,'');
              }
              These can then be used like this:
              Code:
              var
                  sOriginal='  text  ',
                  sTrim=sOriginal.trim(),
                  sLTrim=sOriginal.ltrim(),
                  sRTrim=sOriginal.rtrim();
              [color=green]/* After execution:
                  sOriginal is '  text  '
                  sTrim is 'text'
                  sLTrim is 'text  '
                  sRTrim is '  text'
              */[/color]
              Last edited by liorean; Mar 26, 2004, 10:19 AM.
              liorean <[[email protected]]>
              Articles: RegEx evolt wsabstract , Named Arguments
              Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
              Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

              Comment


              • #8
                Q: Why does parseInt('08') generate 0?

                A: Because JavaScript integers are automatically radix detected. A number starting with 0 is considered to be octal, a number starting with 0x or 0X is considered to be hexadecimal, all other numbers are considered to be decimal. In octal, the digits range from 0 to 7, and thus the 8 is an illegal digit.

                How to fix it? That is easy. You can override the JavaScript automatic radix detection by providing a second argument to the parseInt function, having a value of 10 (for decimal numbers). Thus, you do it like this:
                Code:
                var nYourNumber=parseInt('08', 10);
                For a more thorough explanation, see my textual explanation or my tabular breakdown of how strings may be converted to numbers in JavaScript.
                Last edited by liorean; Jun 27, 2006, 03:57 PM.
                liorean <[[email protected]]>
                Articles: RegEx evolt wsabstract , Named Arguments
                Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
                Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

                Comment


                • #9
                  Q: How do I read/write files?

                  A: Pure client-side JavaScript cannot write files to the server because it simply was never intended to and moreover, that's what server-side languages are used for. Perhaps there are security reasons among others for this as well.

                  As for reading files with JavaScript, this is completely possible and done quite easily if you use something like Vlad's script or David's script.
                  Last edited by fredmv; Mar 4, 2004, 02:52 AM.
                  Moderator @ WebDeveloper.com
                  Mentor @ WebXpertz.net

                  Comment


                  • #10
                    Q: How do I get multiple scripts to work on a single page?

                    A: The short (not recommend) answer is to rename all of the variable and function names in the second instance of the script thus preventing them from conflicting.

                    The longer (recommend) answer would be to rewrite the script in an object-oriented fashion. The reason you'd do it like this is because this is inherently how object-oriented code is intended to work: with multiple instances. This is true because when you call the constructor for that object, all variables become internal properties of it therefore completely removing the chance of anything conflicting between the two scripts. Also note by making it an object you can have as many instances of it on a page as you'd like — it's not only limited to two.

                    For more information on this, check the following threads:
                    Last edited by fredmv; Mar 4, 2004, 02:52 AM.
                    Moderator @ WebDeveloper.com
                    Mentor @ WebXpertz.net

                    Comment


                    • #11
                      Q: How do I convert a decimal number to hexadecimal, and the other way around?

                      A: For converting a hexadecimal number to a decimal number, you use the parseInt function with a radix of 16, like this:
                      Code:
                      var nDecimal=parseInt(sHexadecimal, 16);
                      where sHexadecimal is a string containing a hexadecimal number.

                      For converting a decimal number to hexadecimal, you use the toString method with an argument of the radix you want to convert to, in this case 16, like this:
                      Code:
                      var sHexadecimal=nDecimal.toString(16);
                      where nDecimal is either a variable name, a number literal wrapped in parentheses, or a function giving a number as return value.
                      liorean <[[email protected]]>
                      Articles: RegEx evolt wsabstract , Named Arguments
                      Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
                      Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

                      Comment


                      • #12
                        Q: How do I add ordinals (st, nd, rd, th) to a number?

                        A: After quite some optimisation, you could end up with a function looking something like this:
                        Code:
                        Number.prototype.toOrdinal=function(m){
                            return (this +
                                ["th","st","nd","rd"][(!(
                                    ((m=this%10) >3) ||
                                    (Math.floor(this%100/10)==1)
                                ))*m]);
                        }
                        and you use it like this:
                        Code:
                        var
                            nNumber=12,
                            sFirstOrdinal=nNumber.toOrdinal(), [color=green]// => '12th'[/color]
                            sSecondOrdinal=(22).toOrdinal(); [color=green]// => '22nd'[/color]
                        Well, I won't bore you with the development procedure of this very slick and optimised function. You can check it out yourself in this thread.
                        Last edited by liorean; Mar 4, 2004, 03:50 AM.
                        liorean <[[email protected]]>
                        Articles: RegEx evolt wsabstract , Named Arguments
                        Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
                        Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

                        Comment


                        • #13
                          Q: How do I use JavaScript in external files?

                          A: This is a question that is seldom answered satisfactory. Well, first of all, you should not include any HTML in your JavaScript file. This means that you should not include things like <script type="text/javascript"><!-- or --></script> in the file. Those belong in the HTML file only.

                          Now, the exact same code should behave exactly the same whether it's included in the document or in a separate file. However, there is one issue you must be aware of with JavaScript files: If the JavaScript is placed in the head of the document, the files will be downloaded as soon as the HTML parser reaches them, and they will be executed as soon as they are finished downloading. This means that you can not rely on them being executed in the order they appear in the head. To get around this, you can make sure no code that should actually execute is present in the JavaScript file, only variable declarations and functions. Then you move the execution of code into the window.onload function where you can rely on all of the JavaScript files being referenced in the head to be loaded. Note that this goes only for scripts included in the head of the document, not scripts in the body of the document.
                          Last edited by liorean; Mar 15, 2004, 02:43 PM.
                          liorean <[[email protected]]>
                          Articles: RegEx evolt wsabstract , Named Arguments
                          Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
                          Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

                          Comment


                          • #14
                            Q. How can I use Javascript to protect my web pages?

                            A. Short answer, you can't.

                            Long Answer:

                            Since visitors to your web site can disable Javascript in their browser, javascript can't be used as a protection mechanism.

                            Even without disabling Javascript I can easily see the whole code for your web page by simply running another javascript which will undo anything you did to make the page unavailable. Search for "Bookmarklets" in Google for a bunch of simple but useful scripts like that which can be set up as Bookmarks (Favorites for you IE users).

                            Please note that "No Right Click" scripts (one of the favorite uses of javascript to "protect" a web page) are considered at best a "waste of time" but more often as "user antagonistic" by most of the regulars here. You can get answers on how to write them, fix them and the like eventually but you may find yourself running a gauntlet of questions about why you would want to do such a thing before you get assistance. Scripts that make it harder to provide help do not endear you to the volunteers who provide the help.
                            Last edited by Roy Sinclair; Mar 15, 2004, 02:36 PM.
                            Check out the Forum Search. It's the short path to getting great results from this forum.

                            Comment


                            • #15
                              Q: How do I shorten my lengthly if() statements?

                              A: There are a number of 'tricks' you can use to do this.

                              1:
                              Take this code:

                              PHP Code:
                              <script type="text/javascript">
                              var 
                              a=prompt("Enter number","");
                              var 
                              b=prompt("Enter number","");
                              if(
                              a==b){
                              alert(true);
                              }
                              else{
                              alert(false);
                              }
                              </
                              script
                              As if() statements always return either true or false, you can just do this:

                              PHP Code:
                              <script type="text/javascript">
                              var 
                              a=prompt("Enter number 2","");
                              var 
                              b=prompt("Enter number 2","");
                              alert(a==b);
                              </
                              script
                              This is alerting the result of the test, which is (a==b).

                              2:
                              PHP Code:
                              <script type="text/javascript">
                              var 
                              a=prompt("Enter number 3","");
                              var 
                              b=prompt("Enter number 3","");
                              if(!
                              a||!b){
                              alert("Enter a number")
                              }
                              else if(
                              a==b){
                              alert("Equal");
                              }
                              else{
                              alert("Not equal");
                              }
                              </
                              script
                              As you can see, this tests whether two inputted numbers are equal, alerting a different message depending on:

                              A) If they don't enter two numbers

                              B) If the numbers are equal

                              C) If the numbers are not equal.

                              As in each if(), else if(), else statement, we are doing the same thing (alerting) but alerting something different we can use this:

                              PHP Code:
                              <script type="text/javascript">
                              var 
                              a=prompt("Enter number 4","");
                              var 
                              b=prompt("Enter number 4","");
                              [
                              B]alert((!a||!b)?"Enter a number":(a==b)?"Equal":"Not equal");[/B]
                              </
                              script
                              Note the line in bold. This is how we write it:

                              First we start with alert(. We then put our first condition (inside the first if()) in brackets. So:

                              alert((!a||!b)

                              We then put a question mark after, to show it's an if() statement. We then put the text to alert if this condition is true, so:

                              alert((!a||!b)?"Enter a number"

                              Instead of else, we put a colon : . We then repeat what we have already done. So:

                              alert((!a||!b)?"Enter a number":(a==b)?"Equal"

                              The bit in bold is the condition for the else if() statement. The bit after is the resulting alert. If there are more else if() statements, we put a colon, and repeat. When we get to the last else, we just put a colon and the text to alert if the previous if() and else if()s were all false. In this case, we put a bracket to close the alert() function. We end up with:

                              alert((!a||!b)?"Enter a number"a==b)?"Equal":"Not equal");

                              3:
                              In if() statements or similar, we never need to use the following:

                              if(a==true)
                              if(b==false)

                              Instead of the first, we just need the a. So:

                              if(a)

                              Instead of the second, we put an ! in front of the variable. So:

                              if(!b)

                              4:
                              Take this:

                              PHP Code:
                              <script type="text/javascript"
                              function 
                              disdate(){ 
                              var 
                              d=new Date(); 
                              var 
                              day=d.getDate(); 

                              if(
                              d.getMonth()==0){
                              var 
                              months="Jan"
                              }
                              else if(
                              d.getMonth()==1){
                              var 
                              months="Feb"
                              }
                              else if(
                              d.getMonth()==2){
                              var 
                              months="Mar"
                              }
                              //repeat right up until:
                              else if(d.getMonth()==11){
                              var 
                              months="Dec"
                              }
                              document.getElementById("thedate").value=months;

                              </
                              script
                              As we are testing a variable against numbers 0-11, we can use an array to store all our months:

                              PHP Code:
                              <script type="text/javascript"
                              function 
                              disdate(){ 
                              var 
                              d=new Date(); 
                              var 
                              day=d2.getDate(); 
                              var 
                              months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; 
                              document.getElementById("thedate").value=months[d.getMonth()]

                              </
                              script
                              All the months are stored in an array named months. We refer to each item like this:

                              months[0] for the first

                              months[1] for the second

                              months[2] for the third etc.

                              Instead of the number, we use d.getMonth() inside the square brackets, as this returns the number of the item we want.

                              Comment

                              Working...
                              X