Random Javascript code snippets
Return to Tutorials index
Random collection of misc. code and snippets
Private variable using closures
function x() {
var id = 0;
return function() { return id++; }
} var makeid = x(); var i = makeid();
var j = makeid();idhas effectively private access, via (and only) via the closure makeid() function.Remembering variables via closures
foo() {
var req = xmlhttp();
req.onreadystatechange = function() { /*closure created here*/
if (req.readyState == 4) {
...
}
}
}Even though the
onreadystatechangeis 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
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
onclickfunctions will refer to x[10], the final/latest value of the the closed variablei(the loop counter variableiis a closed variable for the inner function within the loop).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 */ }Defining object methods
function MyObj() {} MyObj.prototype = {
foo: function () {
alert(this);
}
...etc..
} var my1 = new MyObj();
my1.foo();Toggling display visibility
var elem = getElement('elem');
elem.style.display = '';use
display: ''as opposed todisplay: 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 (sinceelem.style.displayhas effectively removed the higher precedence inline style, but the document level declaration is unaffected and will now apply). So either:- Don't use both non-inline styles and inline styles when toggling display property via
style.display = ...(only use inline styles) - or, change the stylesheet/classname as well as the display property if using classname styles or both inline/non-inline at the same time.
- Don't use both non-inline styles and inline styles when toggling display property via
Changing CSS for an element
//only changes/modifies inline style
elem.style.xxx = ...
//classname
elem.className = ...Either inline styles or className can be used.
Use className
elem.className = 'foo';
Use
classNameand notclass(since class can be a reserved word).Use cssFloat
elem.cssFloat = 'left';
Use
cssFloatfor the CSS float property and notfloat, since float is a reserved word in JS.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
add,removeandtogglemethods.var cl = elem.classList;
cl.add('foo');
cl.toggle("bar");See: Mozilla docs
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 0orundefinedinstead) 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
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
eventobject 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). Theevent.targetalways remains the original element upon which received the initial event (click, etc).If
thisis 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 thethisobject is automatically set to the element on which the event was invoked.Further reading see: quirksmode, another 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/onmouseoutcan 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.foofoois only available if either is true:- it is set in an INLINE style definition on 'x'
- if it was previously assigned in JS (before it is accessed later), like:
$('x').style.foo= 4
Otherwise,
foois not available.This is a common issue when accessing
leftandtopstyle 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-divy-divz-divGet all applicable CSS rules
To get all styles applicable to an element (whether inline
Random Javascript code snippets的更多相关文章
- vscode & code snippets
code snippets vscode & code snippets https://github.com/xgqfrms/FEIQA/tree/master/000-xyz/templa ...
- Code Snippets 代码片段
Code Snippets 代码片段 1.Title : 代码片段的标题 2.Summary : 代码片段的描述文字 3.Platform : 可以使用代码片段的平台,有IOS/OS X/ ...
- Xcode开发中 Code Snippets Library 的相关用法
当在进行项目的时候,总会遇到很多相同的写法.因此,我们可以使用Code Snippets Library 来进行代码小片段的“封装”: 以Xcode中常用的属性为例: 使用步骤如下: 1.在Xcode ...
- Xcode开发技巧之Code Snippets Library
http://blog.csdn.net/lin1986lin/article/details/21180007 目录(?)[-] 引言 什么是Code Snippets 如何新建Code Snipp ...
- Problem and Solution Code Snippets
(积累知识,遇到发展,本文仅用于备忘录,不时它需要召回准备) Problem: 依据String的大小来调整Label的frame.在view中又一次更新views的layout并显示. Soluti ...
- Sublime Text3—Code Snippets(自定义代码片段)
摘要 程序员总是会不断的重复写一些简单的代码片段,为了提高编码效率,我们可以把经常用到的代码保存起来再调用. 平时用sublime安装各种插件,使用Tab键快速补全,便是snippets(可译为代码片 ...
- iOS开发-代码片段(Code Snippets)提高开发效率
简介 在 XCode4 引入了一个新特性,那就是“代码片段(Code Snippets)”.对于一些经常用到的代码,抽象成模板放到 Code Snippets 中,使用的时候就只需要键入快捷键就可以了 ...
- Javascript Code Style Guide
本指南采用的Airbnb发布的基于ES5的JavaScript Code Style. ES5 英文版:https://github.com/airbnb/javascript/tree/es5-de ...
- jshint-eclipse: JavaScript Code Quality Plugin for Eclipse
https://blog.oio.de/2012/03/26/jshint-eclipse-javascript-code-quality-plugin-for-eclipse/ techscou ...
随机推荐
- MVC中关于Membership类跟数据库的问题
Membership它们用的是ASPNETDB这个数据库,但我们可以使用我们自定义的数据库,然而除非我们自定义的数据库有着跟这个ASPNETDB一样的模式,否则ASP.NET提供的默认的SqlMemb ...
- BFS与DFS
DFS:使用栈保存未被检测的结点,结点按照深度优先的次序被访问并依次被压入栈中,并以相反的次序出栈进行新的检测. 类似于树的先根遍历深搜例子:走迷宫,你没有办法用分身术来站在每个走过的位置.不撞南山不 ...
- Visual Studio 设置多核编译
1.选择一个指定项目右击 -> 属性 -> 配置属性 -> C/C++ -> 命令行 在附加选项中输入:/MP4 或者/MP8 等,后面的那个数字是指定CPU 核的数量,可以自 ...
- virtualBox 打开旧的ubuntu虚拟机镜像时找不到网卡的解决方法
一 环境: ubuntu v8.04 virtualbox _v4.3 二 操作 1 按正常创建新的虚拟机, 然后在选择虚拟硬盘界面选择使用旧的ubuntu虚拟机 2 打开虚拟机 删除/etc/ude ...
- logstash 配置 logstash-forwarder (前名称:lumberjack)
logstash-forwarder(曾名lumberjack)是一个用go语言写的日志发送端, 主要是为一些机器性能不足,有性能强迫症的患者准备的. 主要功能: 通过配置的信任关系,把被监控机器的日 ...
- 尚学堂Spring视频教程(一):模拟Spring
Spring简单的说就是作为控制反转的容器,看这篇文章前需要先搞懂“控制反转和依赖注入“这个设计模式 我们先来模拟Spring,实现用户添加的功能,新建WEB项目”Spring_0100_Abstra ...
- 动手学servlet(五) 共享变量
1. 无论对象的作用域如何,设置和读取共享变量的方法是一致的 -setAttribute("varName",obj); -getAttribute("varName&q ...
- 单片机联网需求攀升 WIZnet全硬件TCP/IP技术崛起
--新华龙电子为韩国WIZnet公司网络芯片授权代理商,具有20多年的专业团队IC应用开发实力-- 如今不管是在企业还是小区.街道,甚至是居民室内,以太网接口无处不在.有鉴于此,电子设备必将向更加智能 ...
- jQuery校验validate详解(转)
jQuery校验 官网地址:http://bassistance.de/jquery-plugins/jquery-plugin-validation 一导入js库 <script src=&q ...
- Hadoop_配置_linux下编译eclipse插件
使用的hadoop版本为hadoop-1.2.1(对应的含源码的安装包为hadoop-1.2.1.tar.gz) 将hadoop和eclipse都解压在home中的用户目录下 /home/chen/h ...
/
/