comp.lang.javascript FAQ - Quick Answers 2009-02-02

Discussion in 'Javascript' started by FAQ server, Feb 2, 2009.

  1. FAQ server

    FAQ server Guest

    comp.lang.javascript FAQ - Quick Answers- 10, Updated October 13, 2008

    1 Meta-FAQ meta-questions

    You are reading the _comp.lang.javascript_ meta-FAQ,
    version 10. It is available on the web at
    <URL: http://www.jibbering.com/faq/index.html > in HTML form.

    This FAQ provides URLs to further information about ECMAScript
    (loosely called javascript), and some hints and tips to make your
    stay in comp.lang.javascript more enjoyable.

    This document was created for three reasons: to help reduce the
    high levels of noise on CLJ, to provide a resource for people
    new to javascript, and to point to locations that contain
    valuable javascript resources.

    Each day, one section of the FAQ is posted for review and questions,
    and as a reminder that the FAQ is available.

    To cope with a desire for additional explanation and detail
    relating to some aspects of the FAQ, an additional resource
    is available at:-

    <URL: http://www.jibbering.com/faq/faq_notes/faq_notes.html >

    It has been provided separately to avoid increasing the size of
    the FAQ to a point where it would be unreasonable to post it to
    the group.

    2 Javascript Tips
    2.1 _Which newsgroups deal with javascript_?
    2.2 _What questions are on-topic for comp.lang.javascript_?
    2.3 _What should I do before posting to comp.lang.javascript_?
    2.4 _Why was my post not answered_?
    2.5 _What is ECMAScript_?
    2.6 _What is JScript_?
    2.7 _What are object models_?
    2.8 _What is the document object model_?
    2.9 _Internationalisation and Multinationalisation in javascript.
    2.10 _I have a question that is not answered in here or
    in any of the resources mentioned here but I'm sure it has been
    answered in comp.lang.javascript. Where are the archives located_?
    2.11 _What does the future hold for ECMAScript_?

    3 Javascript Resources
    3.1 _What books cover javascript_?
    3.2 _What online resources are available_?

    4 Quick Answers: Numbers
    4.1 _How do I convert a Number into a String with exactly 2 decimal places_?

    When formatting money for example, to format 6.57634 to
    6.58, 6.5 to 6.50, and 6 to 6.00?

    Rounding of x.xx5 is uncertain, as such numbers are not
    represented exactly. See the section on "simple decimal arithmetic"
    for Rounding issues.
    N = Math.round(N*100)/100 only converts N to a Number of value
    close to a multiple of 0.01; but document.write(N) does not give
    trailing zeroes.

    ECMAScript Ed. 3.0 (JScript 5.5 [but buggy] and JavaScript 1.5)
    introduced Number.prototype.toFixed, the main problem
    with this is the bugs in JScript's implementation.

    Most implementations fail with certain numbers, for example 0.07.
    The following works successfully for M>0, N>0:

    function Stretch(Q, L, c) { var S = Q
    if (c.length > 0) {
    while (S.length < L) {
    S = c+S;
    }
    }
    return S;
    }

    function StrU(X, M, N) { // X>=0.0
    var T, S = String(Math.round(X * Number("1e" + N)));
    if (S.search && S.search(/\D/) != -1) {
    return '' + X;
    }
    with (String(Stretch(S, M+N, '0')))
    return substring(0, T = (length-N)) + '.' + substring(T);
    }

    function Sign(X) {
    return X > 0 ? "+" : X < 0 ? "-" : " ";
    }

    function StrS(X, M, N) {
    return Sign(X) + StrU(Math.abs(X), M, N);
    }

    Number.prototype.toFixed = function(n){
    return StrS(this, 1, n);
    };



    <URL: http://www.merlyn.demon.co.uk/js-round.htm >
    <URL: http://msdn2.microsoft.com/en-us/library/sstyff0z.aspx >


    4.2 _Why does simple decimal arithmetic give strange results_?

    For example, 5 * 1.015 does not give exactly
    5.075 and 0.06+0.01 does
    not give exactly 0.07 in javascript.

    ECMAScript numbers are represented in binary as IEEE-754 (IEC 559)
    Doubles, with a resolution of 53 bits, giving an accuracy of
    15-16 decimal digits; integers up to about 9e15 are precise, but
    few decimal fractions are. Given this, arithmetic is as exact
    as possible, but no more. Operations on integers are exact if
    the true result and all intermediates are integers within that
    range.

    In particular, non-integer results should not normally be
    compared for equality; and non-integer computed results
    commonly need rounding; see 4.6.

    <URL: http://msdn2.microsoft.com/en-us/library/7wkd9z69.aspx >
    <URL: http://www.merlyn.demon.co.uk/js-misc0.htm#DW4 >


    Otherwise, use Math.round on the results of expressions which
    should be of integer value.

    4.3 _Why does K = parseInt('09') set K to 0_?

    Method parseInt generally needs a
    second parameter, radix, for the base (value between 2 and 36).

    If radix is omitted, the base is determined by the contents of
    the string. Any string beginning with '0x' or '0X' represents a
    hexadecimal number. A string beginning with a leading 0 is
    parsed as octal (octal digits are 0-7). The string '09'
    is converted to 0.

    To force use of a particular base, use the radix
    parameter: parseInt("09", base).


    If base 10 is desired,
    the unary + operator can be an option. Example:

    var s = '-09.1'; // Input string.
    var j = +s; // Convert to number. Result: -9.1
    var n = j|0; // Chop off decimal (convert ToInt32). Result: -9

    <URL: http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/parseInt >
    <URL: http://msdn2.microsoft.com/en-us/library/x53yedee.aspx >
    <URL: http://docs.sun.com/source/816-6408-10/toplev.htm#1064173 >
    <URL: http://www.jibbering.com/faq/faq_notes/faq_notes.html#FAQN4_12 >


    4.4 _Why does 1+1 equal 11_? or How do I convert a string to a number?

    Variables are not typed; their values are. The conversion between a
    string and a number happens automatically. Since plus (+) is
    also used as in string concatenation, '1' + 1 is equal to '11'.
    The string determines what + does. To overcome this, first convert the
    string to a number. For example: +varname or Number(varname) or
    parseInt(varname, 10) or parseFloat(varname).
    Form control values are strings, as is the result from a prompt
    dialog. Convert these to numbers before performing addition by using
    the unary + operator: +'1' + 1 result is 2.

    Additional Notes:
    <URL: http://www.jibbering.com/faq/faq_notes/type_convert.html >
    <URL: http://msdn2.microsoft.com/en-us/library/67defydd.aspx >


    4.5 _How do I generate a random integer from 1 to N_?
    Math.random() returns a value R such that 0 <= R < 1.0; therefore:


    // positive integer expected
    function Random(j) {
    return Math.floor(j * Math.random());
    }



    - gives an evenly distributed random integer in the range from
    0 to x-1 inclusive; use Random(N)+1 for 1 to N.

    <URL: http://msdn2.microsoft.com/en-us/library/41336409.aspx >
    <URL: http://docs.sun.com/source/816-6408-10/math.htm >

    How to Deal and Shuffle, see in:
    <URL: http://www.merlyn.demon.co.uk/js-randm.htm >



    5 Quick Answers
    5.1 _How do I protect my javascript code_?

    With clientside javascript you can't as your code is distributed
    in source form and is easily readable. With JScript, there is the
    Script Encoder (see MSDN), but this is nothing more than obfuscation.
    Disabling the right mouse button also does nothing to protect
    your script in a Web browser.

    Your code is likely protected under copyright laws. See:

    <URL: http://www.wipo.int/about-ip/en/copyright.html >
    <URL: http://webdesign.about.com/od/copyright/Copyright_Issues_on_the_Web_Intellectual_Property.htm >


    5.2 _How can I disable the back button in a web browser_?

    You can't. The browser's history cannot be modified. However, you
    can use location.replace(url); in some browsers to replace
    the current page in the history.

    <URL: http://msdn2.microsoft.com/en-us/library/ms536712.aspx >
    <URL: http://docs.sun.com/source/816-6408-10/location.htm#1194240 >


    5.3 _How can I access the client-side filesystem_?

    Security means that by default you can't. In a more restricted
    environment, there are options. For example, using LiveConnect
    to connect to Java with Netscape, and using the FileSystemObject
    in IE. Check Google Groups archives <URL: http://groups.google.com/group/comp.lang.javascript/topics >
    for previous posts on the subject.

    <URL: http://msdn2.microsoft.com/en-us/library/z9ty6h50.aspx >
    <URL: http://www.javaworld.com/javaworld/jw-10-1998/jw-10-apptowin32.html >


    5.4 _How can I see in javascript if a web browser accepts cookies_?

    Write a cookie and read it back and check if it's the same.

    <URL: http://www.w3schools.com/js/js_cookies.asp >

    Additional Notes:

    <URL: http://www.jibbering.com/faq/faq_notes/cookies.html >
    <URL: http://www.ietf.org/rfc/rfc2965.txt >
    <URL: http://www.galasoft-lb.ch/myjavascript/consulting/2001012701/ >
    <URL: http://www.cookiecentral.com/ >


    5.5 _How can I prevent access to a web page by using javascript_?

    In practice you can't. While you could create a suitable
    encryption system with a password in the page, the level of
    support you need to do this means it's always simpler to do it
    server-side. Anything that "protects" a page
    other than the current one is definitely flawed.

    5.6 _How do I communicate between frames in a web browser_?

    To reference another frame, you simply need to step through the
    frame hierarchy: parent is the page the frame is
    definedin, parent.framename is another frame in the same
    frameset. To access a variable called Moomin in a frame called Snork you
    would use parent.Snork.Moomin. To call the function Snufkin
    in that frame you would use parent.Snork.Snufkin().

    Note that it is not possible to communicate between frames on
    different domains this way.

    5.7 _How do I find the size of the window_?

    Here is a detailed explanation of a cross-browser strategy to
    find the dimensions of the viewport, excepting all chrome
    (excludes scrollbars, et c).

    We can consider various properties:


    window.innerWidth
    document.clientWidth
    document.documentElement.clientWidth
    document.body.clientWidth



    Of the browsers that have an innerWidth property, most
    include scrollbar dimensions. Some versions of KHTML browsers
    (including Safari 2) do _not_ include scrollbar width.

    The window.inner* properties are unreliable and not
    useful here. We don't want scrollbar dimensions included.

    document.clientWidth


    Certain versions of KHTML, including Safari 2, have
    document.clientHeight and document.clientWidth
    properties. Where supported, these rare properties accurately
    return the height and width of the viewport, without including
    scrollbar dimensions.


    document.documentElement.clientWidth
    document.body.clientWidth



    MSHTML (Trident), Firefox (Gecko), Opera (Presto), and Safari
    (Webkit) all support clientHeight on document.body
    and document.documentElement. The difficulty is figuring out
    which one is reliable. In other words which object to get the
    clientHeight property from:documentElement or body?

    What the number returned from either of these properties
    represents depends on the environment. The environment includes
    the browser, its version, and the rendering mode of the document.
    In quirks mode, we'll mostly want to use body.clientHeight
    (except for in Safari 2).

    document.body.clientHeight


    Some environments will return the viewport height. Others will
    return 0. Yet others will return the clientHeight of
    the BODY element.

    document.documentElement.clientHeight


    This is the more "standard" property for getting the height of
    the viewport. It usually "works" in modern browsers in
    standards mode. Notable exceptions include Safari 2 and
    Opera <= 9.25, both of which return the clientHeight
    of the html_element_. (Oddly, Opera <= 9.25
    in standards mode returns the width of the viewport for
    documentElement.clientWidth).

    With the exception of Safari 2, body.clientHeight is reliable
    where documentElement.clientHeight is found to be unreliable.
    For example, in Safari 3+, Opera, and Mozilla, all in quirks mode,
    document.documentElement.clientHeight returns the clientHeight
    of the html element (this may seem unsurprising but
    it is not what we want).

    Conversely, document.body.clientHeight will return
    the height of the viewport in most cases where
    document.documentElement.clientHeight does not. An exception
    to that is Safari 2, where documentElement.clientHeight
    and body.clientHeight both return the height of their
    corresponding element (not what we want).

    By using a combination of Feature Testing and Capability Testing,
    the dimensions of the viewport can be strategically retrieved
    from the property that works in the environment the script is
    running in. The trick is determining which property willgive us
    the value we want.

    Since document.clientHeight is reliable where
    (rarely) supported, and since browsers that support this property
    don't return the viewport dimensions from
    document.body.clientHeight or
    document.documentElement.clientHeight, this should be the
    very first condition:


    // Safari 2 uses document.clientWidth (default).
    if(typeof document.clientWidth == "number") {
    // use document.clientWidth.
    }



    The next strategy is to determine if
    document.documentElement.clientHeight property is unreliable.
    It is deemed "unreliable" when it is either 0 or taller
    than the viewport.

    Determining if documentElement.clientHeight is 0 is easy.
    The result is stored in a variable IS_BODY_ACTING_ROOT.


    var docEl = document.documentElement,
    IS_BODY_ACTING_ROOT = docEl && docEl.clientHeight === 0;
    docEl = null;



    To determine if documentElement.clientHeight returns
    a value taller than the viewport, we need a Capability Test.
    If we can force documentElement to be very tall
    (taller than a normal viewport) we can then check to see if
    documentElement.clientHeight returns that "very tall" number.
    If it does, then it is unreliable.

    We can force documentElement to be taller than the viewport
    (or any "normal" viewport) by adding a div to the body,
    give that div a height larger than any normal monitor,
    and then check to see if documentElement.clientHeight is
    that high (or "almost" that high, to account for documentElement
    having a border).


    // Used to feature test Opera returning wrong values
    // for documentElement.clientHeight.
    // The results of this function should be cached,
    // so it does not need to be called more than once.
    function isDocumentElementHeightOff(){
    var d = document,
    div = d.createElement('div');
    div.style.height = "2500px";
    d.body.insertBefore(div, d.body.firstChild);
    var r = d.documentElement.clientHeight &> 2400;
    d.body.removeChild(div);
    return r;
    }



    We can use this function to see if we should use
    body.clientHeight, instead. (but only after checking if
    document.clientHeight is supported).


    // Safari 2 uses document.clientWidth (default).
    if(typeof document.clientWidth == "number") {
    // use document.clientHeight/Width.
    }
    else if(IS_BODY_ACTING_ROOT || isDocumentElementHeightOff()) {
    // use document.body.clientHeight/Width.
    } else {
    // use document.documentElement.clientHeight/Width.
    }



    The preceding strategy was developed by Garrett Smith with input
    from John David Dalton. A complete and tested example can be found
    in APE Library under APE.dom.getViewportDimensions.
    Source code:
    <URL: http://dhtmlkitchen.com/ape/build/dom/viewport-f.js >.
    APE is publicly released under Academic Free License.
    APE home: <URL: http://dhtmlkitchen.com/ape/ >.

    Note: The dimensions cannot be determined accurately until after
    the document has finished loading.

    <URL: http://msdn2.microsoft.com/en-us/library/ms533566.aspx >
    <URL: http://developer.mozilla.org/en/DOM/window.innerWidth >
    <URL: http://dev.opera.com/articles/view/using-capability-detection/ >


    5.8 _How do I check to see if a child window is open, before opening another_?


    var myWin;
    function openWin(aURL) {
    if (!myWin || myWin.closed ) {
    myWin = window.open(aURL,'myWin');
    } else {
    myWin.location = aURL;
    myWin.focus();
    }
    }


    <URL: http://msdn2.microsoft.com/en-us/library/ms533574.aspx >
    <URL: http://docs.sun.com/source/816-6408-10/window.htm#1201877 >


    5.9 _Why does framename.print() not print the correct frame in IE_?

    IE prints the frame that has focus when you call the print
    method frameref.focus();frameref.print();
    <URL: http://msdn2.microsoft.com/en-us/library/ms976105.aspx >


    5.10 _How do I get the value of a form control_?

    In HTML documents, named forms may be referred to as named
    properties of the document.forms collection, and named form
    controls may be referred to as named properties of the form's
    elements collection:


    var frm = document.forms["formname"];
    var contrl = frm.elements["elementname"];



    The (string) value property of such controls can be read
    directly from the element:-


    var value = contrl.value;
    value = +contrl.value; //string to number: see 4.2



    Some exceptions would be:

    First Exception: Where the control is a SELECT element, and
    support for older browsers, such as NN4, is required:


    var value = contrl.options[contrl.selectedIndex].value;



    Second Exception: Where several controls share the same name,
    such as radio buttons. These are made available as collections
    and require additional handling. For more information, see:-

    <URL: http://www.jibbering.com/faq/faq_notes/form_access.html >


    Third Exception: File inputs. Most current browsers do not allow
    reading of type="file" input elements in a way that is useful.

    5.11 _How do I close a window and why does it not work on the first one_?

    Use windowRef.close(), where windowRef is a window object
    reference, such as window, top, parent, self, or a reference
    obtained from the window.open() method. You can only close
    windows opened by scripts, no others.

    <URL: http://msdn2.microsoft.com/en-us/library/ms536367.aspx >
    <URL: http://docs.sun.com/source/816-6408-10/window.htm#1201822 >
    <URL: http://developer.mozilla.org/en/docs/DOM:window.open#FAQ >


    5.12 _How do I modify the content of the current page_?

    Using the non-standard but widely implemented innerHTML property:
    <div id="anID">Some Content</div> with script:


    document.getElementById("anID").innerHTML =
    "Some <em>new</em> Content";



    Where "anID" is the (unique on the HTML page)
    id attribute value of the element to modify.

    If the new content is only text and does not need to replace existing HTML,
    it is more efficient to modify the data property of a text node.


    document.getElementById("anID").firstChild.data = "Some new Text";



    Note: Make sure the element exists on the page (and has been parsed) before trying to
    reference it.

    <URL: http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-FF21A306 >
    <URL: http://msdn.microsoft.com/en-us/library/cc304097(VS.85).aspx >
    <URL: http://msdn2.microsoft.com/en-us/library/ms533897.aspx >
    <URL: http://developer.mozilla.org/en/Whitespace_in_the_DOM >
    <URL: http://developer.mozilla.org/en/docs/DOM:element.innerHTML >
    <URL: http://www.jibbering.com/faq/faq_notes/alt_dynwrite.html >


    5.13 _How do I trim whitespace_?

    Use a regular expression:


    function trimString(s) {
    return s.replace(/^\s+|\s+$/g,'');
    }



    <URL: http://docs.sun.com/source/816-6408-10/regexp.htm >
    <URL: http://msdn2.microsoft.com/en-us/library/6wzad2b2.aspx >
    <URL: http://en.wikipedia.org/wiki/Regular_expression >
    <URL: http://www.merlyn.demon.co.uk/js-valid.htm >


    5.14 _How do I force a reload from the server/prevent caching_?

    To reload a page, use location.reload(). However, this depends
    upon the cache headers that your server sends. To change this,
    you need to alter the server configuration. A quick fix on the
    client is to change the page URI so that it contains a unique
    element, such as the current time. For example:
    location.replace(location.href+'?d='+new Date().valueOf())
    If the location.href already contains a query String, use:
    location.replace(location.href+'&d='+new Date().valueOf())
    <URL: http://www.mnot.net/cache_docs/ >
    <URL: http://docs.sun.com/source/816-6408-10/date.htm >


    5.15 _How do I get a perl/asp/php variable into client-side javascript_?

    Use the server-side language to generate the javascript:


    var jsvar = "<%= aspvar %>";
    var jsvar = "<?php echo $phpvar ?>";


    5.16 _Why do I get permission denied when accessing a frame/window_?

    In the normal browser security model, it is impossible for a
    script from one domain to access the properties of pages served
    from another domain, or a different protocol. Any attempt to
    access a property in such cases will result in a "Permission
    Denied" error. Signed scripts or trusted ActiveX objects can
    overcome this in limited situations.

    <URL: http://msdn2.microsoft.com/en-us/library/ms533028.aspx >


    5.17 _How do I make a 10 second delay_?

    There is no built-in way to pause execution in javascript such
    as a sleep function, but hosts usually provide a method of some
    form. Web browsers are designed for event driven programming and
    only provide the setTimeout and setInterval functions
    to facilitate timed delays. The delay before calling Snork may
    exceed the second parameter to setTimeout and setInterval
    due to implementation differences among browsers.

    To call the function Snork(), approximately 10 seconds
    after the function Moomin() completes, you would do this:


    Moomin();
    setTimeout(Snork,10000);



    Script execution is not stopped, and adding Snufkin() after the
    setTimeout line would immediately execute the function Snufkin()
    before Snork().

    Achieving delays through running a loop of some sort for a pre-defined
    period is a bad strategy, as that will inhibit whatever was supposed to
    be happening during the delay, including blocking user interation.

    Other (less event driven) hosts have different wait functions,
    such as WScript.Sleep() in the Windows Script Host.

    <URL: http://msdn2.microsoft.com/en-us/library/ms536753.aspx >
    <URL: http://docs.sun.com/source/816-6408-10/window.htm#1203758 >
    <URL: http://en.wikipedia.org/wiki/Event-driven_programming >
    <URL: http://jibbering.com/faq/faq_notes/misc.html#mtSetTI >


    5.18 _How do I change print settings with window.print()_?

    In a normal security environment, you can't change anything. The
    page stylesheet rules provide some options, but are not supported
    in browsers yet. If you can, use an ActiveX or Plugin ScriptX and
    Neptune from Meadroid to give you more control for Windows
    versions of Internet Explorer, Netscape, and Opera.

    <URL: http://www.meadroid.com/scriptx/ >
    <URL: http://msdn2.microsoft.com/en-us/library/ms976105.aspx >


    5.19 _I have <a href="javascript:somefunction()"> what ... _?

    Whatever the rest of your question, this is generally a very bad idea.
    The javascript: pseudo protocol was designed to replace the
    current document with the value that is returned from the expression.
    For example:


    <a href="javascript:'&lt;h1&gt;' + document.lastModified + '&lt;/h1&gt;'">lastModified</a>



    will result in replacing the current document with the value
    returned from document.lastModified, wrapped in an <h1>
    tag.

    When the expression used evaluates to an undefined value
    (as some function calls do), the contents of the current page are not
    replaced. Regardless, some browsers (notably IE6) interpret this as
    navigation and will enter into a 'navigation' state where GIF
    animations will stop working.

    It is also possible for IE to be configured such that it supports
    javascript but not the javascript: protocol. This results
    in the user seeing a protocol error for javascript: URIs.

    The javascript: pseudo protocol creates accessibility and
    usability problems in user agents that do not support javascript, or
    have javascript disabled. It provides no fallback for when the script
    is not supported.

    Instead, use
    <a href="something.html" onclick="somefunction();return false">
    where something.html is a meaningful alternative. Alternatively,
    attach the click callback using an event registry.

    <URL: http://www.useit.com/alertbox/20021223.html >


    5.20 _My element is named myselect[], how do I access it_?

    Form controls with any "illegal" characters can be accessed with
    formref.elements["myselect[]"] - The bracket characters,
    amongst others, are illegal in ID attributes and javascript
    identifiers, so you should try to avoid them as browsers may
    handle them incorrectly.

    <URL: http://msdn2.microsoft.com/en-us/library/ms537449.aspx >
    <URL: http://docs.sun.com/source/816-6408-10/form.htm >
    <URL: http://www.jibbering.com/faq/faq_notes/faq_notes.html#FAQN4_25 >


    5.21 _How do I detect Opera/Netscape/IE_?

    The navigator object contains strings which
    specify the browser and version; however, this is in general not
    very genuine. Mozilla (and therefore Netscape 6+) allows this to
    be freely set, and Opera and IE allow it to be modified. There
    are also at least 25 other javascript capable browsers with
    their own strings here.

    Generally though, you don't need to identify which browser is
    being used. There are alternative techniques, but which one you
    choose depends on why you want to redirect browsers. If it's to
    offer different CSS stylesheets, then <URL: http://w3development.de/css/hide_css_from_browsers/ >
    shows many techniques. For Scripting, _object_ detection
    is a better method to use.
    <URL: http://www.quirksmode.org/js/support.html >
    It is also known as feature detection.

    Object/feature detection means checking that the object you wish
    to use is supported by the browser before using it. This means
    that you don't need to know what browsers support what methods,
    and your code will automatically be usable on any browser that
    can execute it.


    if (document.getElementById &&
    document.getElementById('el') &&
    document.getElementById('el').style ) {
    // We know that this browser supports getElementById and has
    // a style object, so we can set a style property.
    document.getElementById('el').style.color = "red";
    }


    Browser bugs can often be detected and overcome in similar ways.

    <URL: http://developer.mozilla.org/en/doc...Developing_Cross_Browser/Cross_Platform_Pages >
    <URL: http://www.jibbering.com/faq/faq_notes/not_browser_detect.html >
    <URL: http://dev.opera.com/articles/view/using-capability-detection/ >
    <URL: http://developer.apple.com/internet/webcontent/objectdetection.html >


    5.22 _How do I disable the right mouse button_?

    The oncontextmenu is a proprietary method and is not supported on
    all browsers.
    <body oncontextmenu="return false">
    5.23 _How do I change the confirm box to say yes/no or default to cancel_?

    The buttons on a confirm box cannot be changed, nor can you
    specify a default button. However, you should be able to change
    the question so that "OK" is suitable as the default.
    e.g. change "We will now buy ourselves a Porsche with your credit
    card, Do you want to continue with this transaction _OK_ Cancel"
    to "We will now buy ourselves a Porsche with your credit card,
    Would you like to abandon this transaction? _OK_ Cancel"

    5.24 _How do I log-out a user when they leave my site_?

    This cannot be done reliably. Here's why:


    The user may disable javascript so the log-out script will
    never execute.

    The user may not be on-line when they close your web page.

    Javascript errors elsewhere in the page may prevent the script
    executing.

    The browser may not support the onunload event, or may not fire
    it under certain circumstances, so the log-out function will
    not execute.


    The URL below has more information.

    <URL: http://groups.google.com/groups?selm=BlmZ7.55691$ >


    5.25 _How do I format the lastModified date with javascript_?

    Apparently, new Date() reads document.lastModified
    correctly, though problems
    can occur if the browser returns only two digits for the year.
    In particular, time offset, field order and separators may vary.
    It is also reliant on the server's clock having been correctly
    set at the time of upload. See the URL
    below.

    <URL: http://www.merlyn.demon.co.uk/js-date2.htm#lM >


    5.26 _Why are my rollovers so slow_?

    Images are cached by the browser depending on the headers sent by
    the server. If the server does not send sufficient information
    for the browser to decide the image is cacheable, the browser
    will check if the image has been updated every time you change the
    src of an image (in some user settings). To overcome this you
    must send suitable headers.

    <URL: http://www.mnot.net/cache_docs/ >


    5.27 _How do I change the text in the url/location bar_?

    This text can only be altered by changing the URL of the page.

    5.28 _How do I prompt a "Save As" dialog for an accepted mime type_?

    It is not possible with client-side javascript.

    Some browsers accept the Content-Disposition header, but this
    must be added by the server. Taking the form:-
    Content-Disposition: attachment; filename=filename.ext
    <URL: http://classicasp.aspfaq.com/general/how-do-i-prompt-a-save-as-dialog-for-an-accepted-mime-type.html >
    <URL: http://support.microsoft.com/kb/q260519/ >


    5.29 _How do I run a server side script_?

    You trigger a server-side script by sending an HTTP request.
    This can be acheived by setting the src of an img,
    Image, frame, or iframe,
    or by using XHR.

    An image will also
    "swallow" the data sent back by the server, so that they will
    not be visible anywhere.


    var dummyImage = new Image();
    dummyImage.src = "scriptURL.asp?param=" + varName;



    Mozilla, Opera 7.6+, Safari 1.2+, and Windows IE 7
    provide the XMLHttpRequest object
    (Windows IE versions 5+, provides ActiveX to acheive an analagous
    effect). XMLHttpRequest can send HTTP requests to
    the server, and provides access the responseText or responseXML
    (when the response is XML), and HTTP header information.

    <URL: http://jibbering.com/2002/4/httprequest.html >
    <URL: http://www.w3.org/TR/XMLHttpRequest/ >
    <URL: http://developer.mozilla.org/en/XMLHttpRequest >
    <URL: http://msdn.microsoft.com/en-us/library/ms537505(VS.85).aspx >


    5.30 _I have window.status="Moomin"; why doesn't the statusbar change_?

    When changing the status in an event (e.g. onmouseover) you
    should return true from the event. Also a number of browsers
    require a short delay before setting the status to overcome their
    default behaviour with the statusbar.
    onevent="setTimeout('window.status=\'Moomin\'',15);"
    Most browsers are configured, by default, to disallow scripts from setting
    the status bar text.

    5.31 _How do I modify the current browser window_?

    In a default security environment you are very limited in how much
    you can modify the current browser window. You can use
    window.resizeTo or window.moveTo to resize or move a
    window respectively, but that is it. Normally you can only
    suggest chrome changes in a window.open.

    <URL: http://msdn2.microsoft.com/en-us/library/ms536651.aspx >
    <URL: http://developer.mozilla.org/en/docs/DOM:window.open >


    5.32 _How do I POST a form to a new window_?

    Use the target attribute on the form, opening a window with
    that name and your feature string in the onsubmit handler of the
    FORM.


    <form action="..." target="wndname" onsubmit="window.open('',this.target,'features');return true;">


    <URL: http://www.htmlhelp.com/reference/html40/forms/form.html >


    5.33 _How do I download a page to a variable_?

    Within a web-page use the XMLHttpRequest object, see:

    <URL: http://jibbering.com/2002/4/httprequest.html >
    <URL: http://www.ajaxtoolbox.com/ >


    5.34 _How do I access a property of an object using a string_?

    There are two ways to access properties: the dot notation and
    the square bracket notation. What you are looking for is the square
    bracket notation in which the dot, and the identifier to its right,
    are replaced with a set of square brackets containing a string. The
    value of the string matches the identifier. For example:-


    //dot notation
    var bodyElement = document.body;

    //square bracket notation, using an expression
    var bodyElement = document["bo"+"dy"];


    <URL: http://www.jibbering.com/faq/faq_notes/square_brackets.html >


    5.35 _When should I use eval_?

    The eval() function should _only_ be used when it is necessary to
    evaluate a string supplied or composed at run-time; the string
    can be anything from a simple (but unpredictable) expression such
    as "12 * 2.54" to a substantial piece of javascript code.

    <URL: http://www.jibbering.com/faq/#propertyAccessAgain >
    <URL: http://www.jibbering.com/faq/faq_notes/square_brackets.html >


    5.36 _Why doesn't the global variable "divId" always refer to the element with id="divId"_?

    Microsoft introduced a shortcut that can be used to reference
    elements which include an id attribute where the
    id becomes a globally-accessible property. Some browsers reproduce
    this behavior. Some, most notably Gecko-based browsers (Netscape and Mozilla),
    do so only in "quirks" mode. The best approach is the document.getElementById
    method, which is part of the W3C DOM standard and implemented
    in modern browsers (including IE from version 5.0). So an
    element with id="foo" can be referenced
    with:-


    var el = document.getElementById("foo");



    Note: make sure not to use the same id twice in the same document
    and do not give an element a name that matches an id
    of another in the same document or it will trigger bugs in MSIE <= 7 with
    document.getElementsByName and document.getElementById.

    <URL: http://developer.mozilla.org/en/doc...e_W3C_DOM#Accessing_Elements_with_the_W3C_DOM >
    <URL: http://www.jibbering.com/faq/faq_notes/faq_notes.html#FAQN4_41 >


    5.37 _How do I open a new window with javascript_?

    New windows can be opened on browsers that support the
    window.open function and are not subject to the action of any
    pop-up blocking mechanism with code such as:-


    var wRef;
    if(window.open){
    wRef = window.open("http://example.com/page.html","windowName");
    }


    <URL: http://developer.mozilla.org/en/docs/DOM:window.open >
    <URL: http://www.infimum.dk/HTML/JSwindows.html >


    5.38 _How do I get my browser to report javascript errors_?

    * Windows IE

    Wait until a little yellow
    triangle appears at the left end of the status bar, double click
    on it and, when the error dialog box appears, check the "Always
    show errors" checkbox it contains.

    Or, Internet Options, Advanced, deselect "Disable Script Debugging",
    select "Display a notification ...".


    * Firefox
    <URL: http://www.getfirebug.com/ >.


    * Opera

    Tools > Advanced > Error console


    <URL: http://dev.opera.com/articles/view/introduction-to-opera-dragonfly/ >

    * Safari

    To display the Develop menu in Safari 3.1 or higher, select
    the checkbox labeled "Show Develop menu in menu bar" in
    Safari's Advanced Preferences panel.


    <URL: http://developer.apple.com/internet/safari/faq.html#anchor14 >

    * Chrome

    JavaScript Console: click the Page menu icon and select
    Developer > JavaScript Console. From here, you'll be
    able to view errors in the JavaScript execution, and enter
    additional javascript commands to execute.



    JavaScript Debugger: available as Page menu icon > Developer
    > Debug JavaScript, the debugger provides a command prompt from which you

    can set breakpoints, backtrace, and more. Type help at the debugger
    command line to get started.


    <URL: http://www.google.com/chrome/intl/en/webmasters-faq.html#jsexec >

    * Mac IE

    Use the Preferences dialog.



    5.39 _What is Ajax_?
    Ajax
    is shorthand for Asynchronous JavaScript And XML. The technology is
    based on the XMLHttpRequest Object.
    At its simplest, it is the sending/retrieving of new data from the server
    without changing URL's or reloading the current page.

    Mozilla Documentation:

    <URL: http://developer.mozilla.org/en/docs/XMLHttpRequest >

    MSDN Documention:

    <URL: http://msdn2.microsoft.com/en-us/library/ms535874.aspx >
    <URL: http://msdn2.microsoft.com/en-us/library/ms759148.aspx >

    Libraries and Tutorial Sites:

    <URL: http://jibbering.com/2002/4/httprequest.html >
    <URL: http://www.ajaxtoolbox.com/ >


    An alternative to the XMLHttpRequest Object is Remote Scripting:

    <URL: http://www.ashleyit.com/rs/main.htm >


    5.40 _Why is my Ajax page not updated properly when using an HTTP GET request in Internet Explorer_?

    Microsoft Internet Explorer caches the results of HTTP GET requests. To ensure that the
    document is retrieved from the server, you will need to use the POST Method.

    <URL: http://msdn2.microsoft.com/en-us/library/ms536648.aspx >



    6 Comments and Suggestions
    6.1 _Why do some posts have <FAQENTRY> in them_?
    6.2 _How do I make a suggestion_?




    1_Meta-FAQ meta-questions_

    see <URL: http://jibbering.com/faq/#FAQ1 >
    Or Wednesdays FAQ posting.

    2_Javascript Tips_

    see <URL: http://jibbering.com/faq/#FAQ2 >
    Or Wednesdays FAQ posting.

    3_Javascript Resources_

    see <URL: http://jibbering.com/faq/#FAQ3 >
    Or Wednesdays FAQ posting.

    4_Quick Answers: Numbers_
    4.1 *How do I convert a Number into a String with exactly 2 decimal places?*
    4.2 *Why does simple decimal arithmetic give strange results?*
    4.3 *Why does K = parseInt('09') set K to 0?*
    4.4 *Why does 1+1 equal 11? or How do I convert a string to a number?*
    4.5 *How do I generate a random integer from 1 to N?*


    5_Quick Answers_
    5.1 *How do I protect my javascript code?*
    5.2 *How can I disable the back button in a web browser?*
    5.3 *How can I access the client-side filesystem?*
    5.4 *How can I see in javascript if a web browser accepts cookies?*
    5.5 *How can I prevent access to a web page by using javascript?*
    5.6 *How do I communicate between frames in a web browser?*
    5.7 *How do I find the size of the window?*
    5.8 *How do I check to see if a child window is open, before opening another?*
    5.9 *Why does framename.print() not print the correct frame in IE?*
    5.10 *How do I get the value of a form control?*
    5.11 *How do I close a window and why does it not work on the first one?*
    5.12 *How do I modify the content of the current page?*
    5.13 *How do I trim whitespace?*
    5.14 *How do I force a reload from the server/prevent caching?*
    5.15 *How do I get a perl/asp/php variable into client-side javascript?*
    5.16 *Why do I get permission denied when accessing a frame/window?*
    5.17 *How do I make a 10 second delay?*
    5.18 *How do I change print settings with window.print()?*
    5.19 *I have <a href="javascript:somefunction()"> what ... ?*
    5.20 *My element is named myselect[], how do I access it?*
    5.21 *How do I detect Opera/Netscape/IE?*
    5.22 *How do I disable the right mouse button?*
    5.23 *How do I change the confirm box to say yes/no or default to cancel?*
    5.24 *How do I log-out a user when they leave my site?*
    5.25 *How do I format the lastModified date with javascript?*
    5.26 *Why are my rollovers so slow?*
    5.27 *How do I change the text in the url/location bar?*
    5.28 *How do I prompt a "Save As" dialog for an accepted mime type?*
    5.29 *How do I run a server side script?*
    5.30 *I have window.status="Moomin"; why doesn't the statusbar change?*
    5.31 *How do I modify the current browser window?*
    5.32 *How do I POST a form to a new window?*
    5.33 *How do I download a page to a variable?*
    5.34 *How do I access a property of an object using a string?*
    5.35 *When should I use eval?*
    5.36 *Why doesn't the global variable "divId" always refer to the element with id="divId"?*
    5.37 *How do I open a new window with javascript?*
    5.38 *How do I get my browser to report javascript errors?*
    5.39 *What is Ajax?*
    5.40 *Why is my Ajax page not updated properly when using an HTTP GET request in Internet Explorer?*


    6_Comments and Suggestions_

    see <URL: http://jibbering.com/faq/#FAQ6 >
    Or Wednesdays FAQ posting.
     
    FAQ server, Feb 2, 2009
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page