Random Javascript Code Snippets

Source: Internet
Author: User
Tags button type unique id

mollypages.org
"You are were wrong case."
To live here's to live. "
Home Pages/database/forms/servlet/javadocs/license & Download/tutorials/cookbook/contact

Return to Tutorials Index

Random collection of Misc. Code and Snippets
    1. Private variable using closures
      function X () {    id = 0;    ID+ +; }    }    var makeid = x (); var i = Makeid (); var j = Makeid ();

      idHave effectively private access, via (and only) via the closure Makeid () function.
    2. Remembering variables via closures
      Foo () {    req = XMLHTTP ();    Req.onreadystatechange = function () {/*closure created here*/        if (req. readyState = 4) {            ...            }        }    }
      Even though onreadystatechange the is a property/method of req, it's not invoked *via* req by the request handling (browser) thread. Since T needs access to itself and can either use a global variable (essentially window.req) or a closure to Ho Ld/access a reference to it.

      See Also:mozilla Developer Docs

    3. Closures has access to variables the can be changed
      x = elements (' a ') for (var i = 0; i < i++)    X[i].onclick = function () {/*...use x[i] here...*/}    }
      All onclick functions would refer to x[10], the final/latest value of the the the Closed variable i (the loop counter variabl E is i a closed variable for the inner function within the loop).
    4. Various Ways for Object creation
      A) New and function definition combined var obj =   new function () {/* stuff */}    {}
    5. Defining Object Methods
      MYOBJ () {}Myobj.prototype = {    foo: function () {        alert (this);        }        ... etc..    } var my1 = new MyObj (); my1. Foo ();
    6. toggling Display Visibility
      var elem = getelement (' elem '); elem.style.display = ';
      Usedisplay: ‘‘As opposed todisplay: block(This uses the default "none" of type which can differ from block or table-row or whatever, but in all cases, makes the Eleme NT visible properly.

      However, setting only elem.style.display = ‘‘ Sets or removes the inline style. If a document level CSS style declaration also exists and applies to this element, then once the inline style is removed, the element would be still is rendered with the document level declaration (since have elem.style.display effectively removed th e higher precedence inline style, but the document level declaration is unaffected and would now apply). So either:

        1. Don ' t use both non-inline styles and inline styles when toggling display property via style.display = ... Line styles)
        2. Or, change the Stylesheet/classname as well as the display property if using classname styles or both inline/non- Inline at the same time.

      See:stack Overflow Thread

    7. Changing CSS for an element
      Only changes/modifies inline styleelem.style.xxx = ...//classnameelem.classname = ...  
      Either inline styles or className can be used.
    8. Use className
      elem.classname = ' Foo ';
      Use and not className class (since class can is a reserved word).
    9. Use CSSFloat
      Elem.cssfloat = ' Left ';
      Use cssFloat of the CSS float property and not float , since float is a reserved word in JS.
    10. use Classlist when elements had multiple classesfor multiple classes, one had to is careful to parse/save the class s Tring properly, for example:
      elem.classname = ' foo bar baz '; 
      using  Classlist  makes working with multiple names easier, with the  add , & nbsp remove  and  Toggle  methods.
      var cl = elem.classlist;cl.add (' foo '); Cl.toggle ("Bar"); 
      See: mozilla Docs
    11. Ways to invoke JS event handlers
      -in html<a href= "Javascript:foo ()" <anyelement onclick= "Javascript:foo ()" <anyelement onclick= "foo ()"  ( The "javascript:" is optional) <form action= "foo ()"  (the "javascript:" is optional)-in JS Codeanyelement.onclick = Foo
      Don ' t return a value in onclick event handlers for HREF's etc, (return void 0 or undefined instead) because in some cases, the Browser would show the return value instead (as if the user navigated to a new page with that value)

      More Reading:quirksmode

    12. DOM 0 Event handlers is methods
      <body><form><button type= ' button ' onclick= "MyFunc (This, ' Button.onclick ', event)" >my button</ Button></form><div onclick= "MyFunc (This, ' Div.onclick ')" >my div</button><script> function MyFunc (Elem, MSG, e) {Console.log (Elem, MSG, e);} </script></body>
      (as a small aside, a button inside a form submits that form unless a type=button is specified, the vagaries of legacy HTML )

      The event object is a available in inline handlers via the ' event ' object. If applicable handlers is declared on the parent elements, then as events bubble up to parent, parent handlers would be invoke D for the parent, again (with ' this ' being the parent, the parent handler is invoked). event.targetthe always remains the original element upon which received the initial event (click, etc).

      If this is isn't passsed in the Inline-handler, this refers to the window where the script was running, in the event handler function itself.

      Event handlers declared in JSbutton.onclick = ...<.code> are methods of the corresponding DOM button object, in which the this object is automatically set to the element on which the event was invoked.

      Further reading see: quirksmode, another great tutorial

  • Using the ID attributewhen the id attribute is used, and all elements should has unique ID ' s. The same ID for multiple elements results in all sorts of problems on IE, even when using something like prototype ' s down/ Up, where we want a unique ID (and there are a unique ID) when the starting downwards from a given element.
  • Programmatic assignment of Classes
    var table = document.getElementById (' mytable '); var rows  = Table.getelementsbytagname (' tr '); for (var i = 0; i < rows . length; i++) {    if (i%2) {        rows[i]. className + = "even";        }    }
    Programmatically adding a class to a table to achieve a zebra stripes effect. JS functions for onmouseover/onmouseout can also is added this.
  • Ease of DOM
    $ (' foo '). Related = $ (' bar ');
    ADD properties to DOM objects themselves to refer to other related DOM objects as needed (this causes no memory leaks in I E since we are staying within the DOM).
  • Force CSS Layout
    Window.resizeby (0,1) window.resizeby (0,-1)
    This forces CSS relayout and rendering updates.
  • Accessing CSS styles from Jsstyles to an element is reflected in the element. StyleProperty. To read a particular style, sayFoo, say:
    $ (' x '). style.foo
    foois only available if either is true:
      1. It is set in a INLINE style definition on ' x '
      2. If it's previously assigned in JS (before it's accessed later), like:
        $ (' x '). style. foo = 4

    Otherwise,foois not available.

    This was a common issue when accessing left and top style properties in a div (where the default left/top is not Availa ble since they were not set in a inline style). The solution is to set these initially, either inline or via JS.

    Working example (in the right column):

    < Pre><style> #x, #y, #z {border:1px solid #ccc; margin:5px; } #y {font-size:2em; left:30px; position:relative; } #z {font-size:2em; position:relative; }</style><script>function Show (name) {var div = document.getElementById (name); Alert ("left=" +div.style.left + "\nfontsize=" +div.style.fontsize); }</script><div onclick = "Show (' X ')" Id=x style= "FONT-SIZE:2EM;" >x-div</div><div style= "position:relative" ><div onclick = "show (' Y ')" id=y> Y-div</div></div><div style= "position:relative" ><div onclick = "Show (' Z ')" id =z style= "left:60px;" >z-div</div></div> x-divy-divz-div
  • Get all applicable CSS Rulesto get all styles applicable to an element (whether inline

Random Javascript Code Snippets

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.