MollyPages.org
"You were wrong case.
To live here is to live."

Return to Tutorials index

Random collection of misc. code and snippets

 
    1. Private variable using closures

      function x() {
      var id = 0;
      return function() { return id++; }
      } var makeid = x(); var i = makeid();
      var j = makeid();

      id has effectively private access, via (and only) via the closure makeid() function.

    2. Remembering variables via closures

      foo() {
      var req = xmlhttp();
      req.onreadystatechange = function() { /*closure created here*/
      if (req.readyState == 4) {
      ...
      }
      }
      }

      Even though the onreadystatechange is a property/method of req, it is 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 hold/access a reference to it.

      See also: mozilla developer docs

    3. Closures have access to variables that can be changed

      x = elements('a')
      for (var i = 0; i < 10; i++)
      x[i].onclick = function() { /*...use x[i] here...*/ }
      }

      All onclick functions will refer to x[10], the final/latest value of the the closed variable i (the loop counter variable i is 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 */ } B) object literal (this is cool since can use data retrieved via JSON as well as saves typing/easier to read anyway).
      var obj = { /* stuff */ }
    5. Defining object methods

      function 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 = '';

      use display: '' as opposed to display: block (this uses the default "none" type which can differ from block or table-row or whatever, but in all cases, makes the element visible properly.

      However, setting elem.style.display = '' only sets or removes the inline style. If a document level css style declaration also exists and applies to that element, then once the inline style is removed, the element will be still be rendered with the document level declaration (since elem.style.display has effectively removed the higher precedence inline style, but the document level declaration is unaffected and will now apply). So either:

      1. Don't use both non-inline styles and inline styles when toggling display property via style.display = ... (only use inline 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 style
      elem.style.xxx = ...
      //classname
      elem.className = ...

      Either inline styles or className can be used.

    8. Use className

      elem.className = 'foo';
      

      Use className and not class (since class can be a reserved word).

    9. Use cssFloat

      elem.cssFloat = 'left';
      

      Use cssFloat for the CSS float property and not float, since float is a reserved word in JS.

    10. Use classList when elements have multiple classes

      For multiple classes, one has to be careful to parse/save the class string properly, for example:

      elem.className = 'foo bar baz';
      

      Using classList makes working with multiple names easier, with the addremove 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 Code
      anyelement.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 will 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 are 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 available in inline handlers via the 'event' object. If applicable handlers are declared on parent elements, then as events bubble up to parent, parent handlers will be invoked for the parent again (with 'this' being the parent when the parent handler is invoked). The event.target always remains the original element upon which received the initial event (click, etc).

      If this is not passsed in the inline-handler, this refers to the window where the script is running, in the event handler function itself.

      event handlers declared in JS button.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: quirksmodeanother great tutorial

  • Using the id attribute

    When the id attribute is used, all elements should have unique id's. The same id for multiple elements results in all sorts of problems in IE, even when using something like prototype's down/up, where we want a unique id (and there is a unique id) when 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 be added this way.

  • 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 IE 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 JS

    Styles for an element are reflected in the element.style property. To read a particular style, say foo, say:

    $('x').style.foo
    

    foo is only available if either is true:

    1. it is set in an INLINE style definition on 'x'
    2. if it was previously assigned in JS (before it is accessed later), like:
      $('x').style.foo = 4

    Otherwise, foo is not available.

    This is a common issue when accessing left and top style properties on a div (where the default left/top are not available 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):

    <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-div
    y-div
    z-div
  • Get all applicable CSS rules

    To get all styles applicable to an element (whether inline

Random Javascript code snippets的更多相关文章

  1. vscode & code snippets

    code snippets vscode & code snippets https://github.com/xgqfrms/FEIQA/tree/master/000-xyz/templa ...

  2. Code Snippets 代码片段

    Code Snippets 代码片段       1.Title : 代码片段的标题 2.Summary : 代码片段的描述文字 3.Platform : 可以使用代码片段的平台,有IOS/OS X/ ...

  3. Xcode开发中 Code Snippets Library 的相关用法

    当在进行项目的时候,总会遇到很多相同的写法.因此,我们可以使用Code Snippets Library 来进行代码小片段的“封装”: 以Xcode中常用的属性为例: 使用步骤如下: 1.在Xcode ...

  4. Xcode开发技巧之Code Snippets Library

    http://blog.csdn.net/lin1986lin/article/details/21180007 目录(?)[-] 引言 什么是Code Snippets 如何新建Code Snipp ...

  5. Problem and Solution Code Snippets

    (积累知识,遇到发展,本文仅用于备忘录,不时它需要召回准备) Problem: 依据String的大小来调整Label的frame.在view中又一次更新views的layout并显示. Soluti ...

  6. Sublime Text3—Code Snippets(自定义代码片段)

    摘要 程序员总是会不断的重复写一些简单的代码片段,为了提高编码效率,我们可以把经常用到的代码保存起来再调用. 平时用sublime安装各种插件,使用Tab键快速补全,便是snippets(可译为代码片 ...

  7. iOS开发-代码片段(Code Snippets)提高开发效率

    简介 在 XCode4 引入了一个新特性,那就是“代码片段(Code Snippets)”.对于一些经常用到的代码,抽象成模板放到 Code Snippets 中,使用的时候就只需要键入快捷键就可以了 ...

  8. Javascript Code Style Guide

    本指南采用的Airbnb发布的基于ES5的JavaScript Code Style. ES5 英文版:https://github.com/airbnb/javascript/tree/es5-de ...

  9. jshint-eclipse: JavaScript Code Quality Plugin for Eclipse

    https://blog.oio.de/2012/03/26/jshint-eclipse-javascript-code-quality-plugin-for-eclipse/   techscou ...

随机推荐

  1. Python xlrd、xlwt、xlutils修改Excel文件

    一.xlrd读取excel 这里介绍一个不错的包xlrs,可以工作在任何平台.这也就意味着你可以在Linux下读取Excel文件.首先,打开workbook:    import xlrdwb = x ...

  2. 转 listener.log文件过大导致oracle数据库连接非常慢

    数据库(31)  最近发现oracle数据库连接非常慢,sqlplus很快,用客户端就很慢,甚至会无响应. 然后服务器内存一下就飙升到了90%,不是表空间占满了,也不是数据库连接数占满了.重启还是一样 ...

  3. mssql整理

    select charindex( 'a ', 'bcad ') 1 删除女性数据2.SELECT * FROM Group2 where PATINDEX('%[吖-做]%',[Nick])=0 找 ...

  4. js运动框架之掉落的扑克牌(重心、弹起效果)

    玩过电脑自带纸牌游戏的同志们应该都知道,游戏过关后扑克牌会依次从上空掉落,落下后又弹起,直至"滚出"屏幕. 效果如图:    这个案例的具体效果就是:点击开始运动,纸牌会从右上角掉 ...

  5. .net 环境下get 获取页面出现乱码问题解决

    不多说了,先上代码: /// <summary> /// 获取页面内容 /// </summary> /// <param name="Url"> ...

  6. (原)Android理论梳理-No1异步处理之Handler相关机制

    1 Handler的基本概念: 什么是handler? Handler是安卓系统的一种回调机制. handler的作用? 他的作用是用于不同线程之间的通讯.一是可以用于子线程与UI线程的数据通信,因为 ...

  7. Java基础知识:代理

    一.代理的概念 动态代理技术是整个java技术中最重要的一个技术,它是学习java框架的基础,不会动态代理技术,那么在学习Spring这些框架时是学不明白的. 动态代理技术就是用来产生一个对象的代理对 ...

  8. java、tomcat环境变量的配置(针对windows)

    重做了下系统. 于是所有的软件都没了. 好吧,我是故意的,就是把那些我不知道的东西都删掉.. 于是问题来了,java安装好了,tomcat也粘贴完了,环境变量怎么办? 好吧,首先从可爱的java或者说 ...

  9. 第一个Leap Motion测试页面 (webgl/three/leapjs/leap)

    div#canvas-frame{ border: none; cursor: pointer; width: 100%; height: 800px; background-color: #EEEE ...

  10. NOIP2008 传纸条

    题目描述 小渊和小轩是好朋友也是同班同学,他们在一起总有谈不完的话题.一次素质拓展活动中,班上同学安排做成一个m行n列的矩阵,而小渊和小轩被安排在矩阵对角线的两端,因此,他们就无法直接交谈了.幸运的是 ...