Announcement

Collapse
No announcement yet.

JavaScript Frequently Asked Questions

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

  • JavaScript Frequently Asked Questions

    This is a thread with some frequently asked JavaScript questions. I have collected some basic JavaScripts here, always check that your question isn't answered here before starting a new thread in this forum. Also remember to search the forums before posting. It's your own time that you save
    If you think something should be added to this thread, just send me a private message.

    JavaScript Resources
    Here are a couple of good JavaScript resources.
    Table of Contents
    The links open in a new window - you can also scroll down this page to view the FAQs.

    1. How do I open a popup window?
    2. How do I put JavaScript to an external .js file?
    3. Where can I learn JavaScript?
    4. Can I create forums, polls, client logins, chats, etc. with JavaScript?
    5. How do I change the text in the browser's status bar?
    6. How do I open a popup window, but without the title bar?
    7. Where can I find some cool scripts?
    8. How do I format a number to a fixed number of decimal places?
    9. Why do parseInt('08') and parseInt('09') generate 0?
    10. How do I get a "set to homepage" link?
    11. How do I get a "bookmark this page" link?
    12. How do I block JavaScript error messages?
    13. How do I disable right clicks?
    14. How do I limit the number of characters in a textarea?
    15. How do I change the src of an image when moving the cursor over it?
    16. How do I preload images?
    17. How about customising the scrollbar?

  • #2
    How do I open a popup window?

    This is probably the most repeatedly asked question in the Client Side Scripting forum. Here is a simple code for opening a popup window from a link:
    Code:
    <a href="http://www.google.com/" target="_blank"
    onclick="window.open(this.href, '', 'width=400,height=350,scrollbars=yes'); return false;">Click here</a>
    It is better to use this code rather than a link that goes to javascript:window.open(), because with this code, people with JavaScript disabled in their browsers will get the page opened in a regular new window, instead of not getting it opened at all.

    If you want to open many popups from a page, with the same window attributes, it is easier to define your own function. Add this JavaScript anywhere between the <head> and </head> tags of the page first:
    Code:
    <script type="text/javascript">
    // <![CDATA[
    
    function openPopup(url){
        window.open(url, '', 'width=400,height=350,scrollbars=yes');
        return false;
    }
    
    // ]]>
    </script>
    Now you only need this link to open a popup:
    Code:
    <a href="http://www.google.com/" target="_blank"
    onclick="return openPopup(this.href);">Click here</a>
    All popups opened using this method have the same attributes though. If you want them same, except for the width and height, you can use this function instead:
    Code:
    function openPopup(url, w, h){
        window.open(url, '', 'width='+w+',height='+h+',scrollbars=yes');
        return false;
    }
    Along with this link:
    Code:
    <a href="http://www.google.com/" target="_blank"
    onclick="return openPopup(this.href, 400, 350);">Click here</a>
    Notice that it doesn't have to be a link; you can add an onclick event to almost any element. For instance, a button:
    Code:
    <input type="button" value="Click here"
    onclick="window.open('http://www.google.com/', '', 'width=400,height=350,scrollbars=yes');">
    or a table cell:
    Code:
    <table>
    <tr>
    <td onclick="window.open('http://www.google.com/', '', 'width=400,height=350,scrollbars=yes');">Go</td>
    </tr>
    </table>
    Notice that you need the return statement only for links; it is there to cancel the link from actually going anywhere. Otherwise you would get the page opened in a regular new window too!

    If you want to open a popup automatically when the page loads, insert this script in the header:
    Code:
    <script type="text/javascript">
    // <![CDATA[
    
    window.open('http://www.google.com/', '', 'width=400,height=350,scrollbars=yes');
    
    // ]]>
    </script>
    Or when the user exits the page:
    Code:
    <script type="text/javascript">
    // <![CDATA[
    
    window.onunload = function(){
        window.open('http://www.google.com/', '', 'width=400,height=350,scrollbars=yes');
    }
    
    // ]]>
    </script>
    "width", "height" and "scrollbars" are attributes specified for the popup window. There are other attributes you can use too; separate the attributes with commas:
    Code:
    attribute            value          description
    width                numeric        Width of the window's document in pixels
    height               numeric        Height of the window's documetn in pixels
    left                 numeric        The window's distance from the left edge of the screen, in pixels
    top                  numeric        The window's distance from the top edge of the screen, in pixels
    directories          yes/no         Show standard browser directory buttons
    location             yes/no         Show the location field (page address field)
    menubar              yes/no         Show the menu at the top of the window
    resizable            yes/no         The window can be resized by the user
    scrollbars           yes/no         Show the horizontal and vertical scrollbars
    status               yes/no         Show the status bar at the bottom of the window
    toolbar              yes/no         Show the standard browser toolbar
    copyhistory          yes/no         Copies the browser's back/forward history to the new window
    fullscreen           yes/no         Opens a fullscreen window (doesn't work in all browsers)
    Please notice that some people use popup blockers. They only allow popup windows to open when the user has clicked a link (requested the popup).

    Comment


    • #3
      How do I put JavaScript to an external .js file?

      Cut all code between the <script> and </script> tags and paste it to a .js file. Don't include HTML commenting (<!-- and -->), or any other HTML tags. To include the file on the page, use this code:
      Code:
      <script type="text/javascript" src="filename.js"></script>
      Make sure the path to the .js file is correct.

      Comment


      • #4
        Where can I learn JavaScript?

        Here are links to a couple of JavaScript tutorials. You can search Google for more.

        Comment


        • #5
          Can I create forums, polls, client logins, chats, etc. with JavaScript?

          Nope. JavaScript is a client-side language; it is executed by your web browser. Hence, it cannot alter files and databases located on a server. JavaScript is used to created dynamic content on a website, and it is extremely powerful for that. It can react on mouse clicks, moves, key presses, window resizes, page/image loads, it can create and delete elements, change their attributes as well as CSS properties, and so much more.

          To make forums, polls and such, you need the opposite to a client-side language; a server-side language. That means a script that is executed by the web server. Popular server-side languages are Perl, PHP, ASP, JSP, Python and ColdFusion, but there are many more. Essential is that your webhost supports the language. They can do what JavaScript can't, and cannot do what JavaScript can.

          Comment


          • #6
            How do I change the text in the browser's status bar?

            By altering window.status; here is a link that changes the status bar text when hovering it, and removes the text when moving the cursor away from it:
            Code:
            <a href="http://www.google.com/" onmouseover="window.status = 'Go to Google'; return true;"
            onmouseout="window.status = ' '; return true;">Google</a>
            If you want to do it automatically:
            Code:
            <script type="text/javascript">
            // <![CDATA[
            
            window.status = 'Welcome to my website!';
            
            // ]]>
            </script>
            Please notice that some people have the status bar hidden in their browsers, and some browsers allow users to disable text changing in the status bar.

            Comment


            • #7
              How do I open a popup window, but without the title bar?

              It is possible, but only in Internet Explorer 5.0 and newer on Windows, and not on Windows XP SP1 or newer. That is due to a bug in Internet Explorer that allows resizing of a fullscreen window. It is called a chromeless window, here is a function for opening one:
              Code:
              <script type="text/javascript">
              // <![CDATA[
              
              function chromelessWindow(url, w, h, l, t){
                  if(document.all && !window.opera && navigator.userAgent.indexOf('Windows') >= 0 &&
                  navigator.userAgent.match(/NT\s*(5\.[1-9]|[6-9]\.\d)/) == null){
                      var win = window.open(url, '', 'fullscreen=1,scrollbars=yes');
                      win.resizeTo(w, h);
                      win.moveTo(l, t);
                      win.navigate(url);
                  }
                  else{
                      window.open(url, '', 'width='+w+',height='+h+',left='+l+',top='+t+',scrollbars=yes');
                  }
              }
              
              // ]]>
              </script>
              It takes five arguments, they're all required:
              Code:
              chromelessWindow('url to open', width, height, left, top);
              Here is an example of calling it:
              Code:
              chromelessWindow('http://www.google.com/', 400, 350, 80, 80);
              From a link:
              Code:
              <a href="http://www.google.com/" target="_blank"
              onclick="chromelessWindow(this.href, 400, 350, 80, 80); return false;">Click here</a>

              Comment


              • #8
                Where can I find some cool scripts?

                There are lots of cool scripts out there that you only need to copy, paste and configure. For instance, drop down menus, mouse trailers, scrollers, text animations, and much more. Here are some JavaScript resources:If you can't find a specific script that you're searching for from any of the resources above, try Google. If it's something small and simple, somebody here may be willing to write a script for you, but always search first.

                Comment


                • #9
                  How do I format a number to a fixed number of decimal places?

                  Code by Jon Hanlon.
                  Code:
                  function formatNumber(expr, decimals) {
                           var str = "" + Math.round( eval(expr) * Math.pow(10,decimals))
                           while (str.length <= decimals) { str = "0" + str } 
                           var decpoint = str.length - decimals; 
                           var result = str.substring(0,decpoint);
                           if (decimals) result += "." + str.substring(decpoint,str.length);
                           return result;
                  }
                  As the Math.round() doesn't give you an option to keep a specified number of decimal places, but simply rounds all decimals off, here is a function that does it. The first argument is the number and the second one is the number of decimal places to keep. Sample usage:
                  Code:
                  alert(formatNumber(783 / 7, 4));  //four decimal places
                  alert(formatNumber(Math.PI, 3));  //three decimal places

                  Comment


                  • #10
                    Why do parseInt('08') and parseInt('09') generate 0?

                    Because the browser detects the radix (the number base) automatically. Any number starting with a zero is considered to be an octal number, and one starting with 0x or 0X is a hexadecimal one. All other numbers are decimal (base-10) numbers.

                    When you are calling parseInt('08'), the browser thinks it's an octal number. In octal, there are only numbers 0 - 7, so the numbers 8 and 9 are illegal and the browser treats them as zeroes, and the result is zero.

                    To fix it, you need to specify the radix yourself so the browser doesn't attempt to auto recognize it. The radix you want is 10:
                    Code:
                    parseInt('08', 10);
                    parseInt('09', 10);
                    Defining the radix yourself is always good to do.

                    Comment


                    • #11
                      How do I get a &quot;set to homepage&quot; link?

                      Here is a link that sets the current page to the browser's start page. It only works in Internet Explorer, and requires the user to confirm when the link has been clicked.
                      Code:
                      <a href="#" onclick="if(document.all && !window.opera){ this.style.behavior='url(#default#homepage)';
                      this.setHomePage(location.href); } return false;">Set page as homepage</a>

                      Comment


                      • #12
                        How do I get a &quot;bookmark this page&quot; link?

                        Here is a link that adds the current page to the browser's bookmarks (favorites). It works in Internet Explorer, Opera and Gecko based browsers.
                        Code:
                        <a href="#" rel="sidebar"
                        onclick="if(document.all && !window.opera){ window.external.AddFavorite(location.href, document.title);
                        return false; }else{ this.title = document.title; }">Add to bookmarks</a>

                        Comment


                        • #13
                          How do I block JavaScript error messages?

                          While you should fix the problem rather than cover it, here is a code snippet that prevents JavaScript error messages from appearing (in most browsers):
                          Code:
                          <script type="text/javascript">
                          // <![CDATA[
                          
                          window.onerror = function(){
                              return true;
                          }
                          
                          // ]]>
                          </script>
                          If you want your own, customized error message:
                          Code:
                          <script type="text/javascript">
                          // <![CDATA[
                          
                          window.onerror = function(msg, file, line){
                              alert('A JavaScript error occured on this page. Please report it to the site\'s author.\n\n' +
                              'File:\t\t' + file + '\n' +
                              'Message:\t\t' + msg + '\n' +
                              'Line:\t\t' + line);
                              return true;
                          }
                          
                          // ]]>
                          </script>

                          Comment


                          • #14
                            How do I disable right clicks?

                            Please, don't bother to. There are many many ways to get around right click disabling:
                            - Choose File->Save As in your browser, you can pick up the images from where you saved the page.
                            - Disable JavaScript in your browser.
                            - Use Opera, Mozilla, or another browser that doesn't let a page disable right clicks at all.
                            - Most keyboards have a button for making a right click (next to Ctrl, Alt, Alt Gr and those), right click disabling doesn't affect that.
                            - You can view the source of the page, pick up the image filenames and type them to the address bar to access them directly.
                            - You can take a screenshot; hit Print Screen (next to F12 on your keyboard) and paste the image to a graphics editor.

                            There are probably other ways too that I've missed. So, the point is, disabling right clicks does NOT protect your images. If you truly wish to protect your images:
                            - Zip them with a password
                            - Save them on a floppy disk
                            - Keep the floppy in sulphuric acid for a couple of days
                            - Break it in pieces
                            - Burn all pieces to ashes
                            - Throw them in the river from the closest bridge.

                            Ok, I hope you get the idea already
                            If you don't want anyone to steal your images, don't publish them on the web! If you really need to, you can put watermarks on the images in a graphics editor to not make them worth stealing. Having a right click protection script on your site does nothing but annoys your visitors off.

                            Comment


                            • #15
                              How do I limit the number of characters in a textarea?

                              Add this code to the page header:
                              Code:
                              <script type="text/javascript">
                              // <![CDATA[
                              function textareaChars(objTextarea, maxLimit, objCountField){
                                  if(objTextarea.value.length > maxLimit)
                                      objTextarea.value = objTextarea.value.substring(0, maxLimit);
                                  if(arguments.length == 3)
                                      objCountField.value = (maxLimit - objTextarea.value.length);
                              }
                              // ]]>
                              </script>
                              You can then control the maxlength of a textarea with:
                              Code:
                              <form>
                              <textarea name="fieldName" rows="6" cols="40" onkeypress="textareaChars(this, 5000);"></textarea>
                              </form>
                              Where "this" should always be kept as "this", and 5000 is the maximum characters allowed. If you wish to use field that shows the number of characters left:
                              Code:
                              <form>
                              <textarea name="fieldName" rows="6" cols="40"
                              onkeypress="textareaChars(this, 5000, this.form.counterField);"></textarea>
                              <input type="text" name="counterField" value="5000" readonly="readonly">
                              </form>

                              Comment

                              Working...
                              X