function () {
        // 第一次……
     function () {
        // 第二次……
$("#id")[0].style.display = 'none';

Set/Clear Default Input Value

very old snippet from CSS-tricks:

$(‘.default-value’).each(function() { var default_value = this.value; $(this).focus(function(){ if(this.value == default_value) { this.value = ”; } }); $(this).blur(function(){ if(this.value == ”) { this.value = default_value; } }); });

clear textbox after form submit

Add an id for the textarea.

<textarea name='comment' id='comment'></textarea>

Hook into the submit process and add:


 input placeholder attribute

adding HTML5 placeholder behavior to the browsers that don’t support it. We are going to use a jQuery plugin by Mathias Bynens. Check out the GitHub repo for details.

Use the plugin as follows:

$('input, textarea').placeholder();

You’ll still be able to use jQuery#val() to get and set the input values. If the element is currently showing a placeholder, .val()will return an empty string instead of the placeholder text, just like it does in browsers with a native @placeholder implementation. Calling .val('') to set an element’s value to the empty string will result in the placeholder text (re)appearing.


The plugin automatically adds class="placeholder" to the elements who are currently showing their placeholder text. You can use this to style placeholder text differently:

input, textarea { color: #000; }
.placeholder { color: #aaa; }
  • Automatically checks if the browser natively supports the HTML5 placeholder attribute for input and textarea elements. If this is the case, the plugin won’t do anything. If @placeholder is only supported for input elements, the plugin will leave those alone and apply to textareas exclusively. (This is the case for Safari 4, Opera 11.00, and possibly other browsers.)
  • Caches the results of its two feature tests in jQuery.fn.placeholder.input and jQuery.fn.placeholder.textarea. For example, if @placeholder is natively supported for input elements, jQuery.fn.placeholder.input will be true. After loading the plugin, you can re-use these properties in your own code.
    • Makes sure it never causes duplicate IDs in your DOM, even in browsers that need an extra input element to fake@placeholder for password inputs. This means you can safely do stuff like:
      <label for="bar">Example label</label>
      <input type="password" placeholder="foo" id="bar">

      And the <label> will always point to the <input> element you’d expect. Also, all CSS styles based on the ID will just work™.


how to use?

Call $(selector).placeholder(options) on an input element with an attribute placeholder.



The following options can be passed to the plugin.

  • activeClass –The class to apply when input is blurred. Defaults to placeholder.
  • focusClass – The class to apply when input is active. Defaults to placeholderFocus.
  • overrideSupport –Pass true to force the plugin to work on browsers which natively support the placeholderattribute. Defaults to false.
  • preventRefreshIssues – Optionally attempt to prevent Firefox from auto filling values on refresh, by turning autocompleteoff. Defaults to true.

Another placeholder:

$('input#search').placeholder({onBlur: "blurred", onChange: "changed"});

.hide() .show()






$(“#id”)[0].style.display = ‘none’;


jquery template


Selects all elements that do not match the given selector.

All selectors are accepted inside :not(), for example: :not(div a) and :not(div,a).


js端的模板,主要用于拼装html字符,因为直接操作dom效率很低。直接用字符串平html代码很难维护,于是就出来这种模式  模板+json(或其他数据) = html字符串。常用的应用场景就是 ajax从后台取到json数据,然后用模板渲染成html,然后更新

In a sense jQuery Templates consists of three plugins: .tmpl(), .tmplItem() and .template(), and each one comes in two flavors: instance plugin and static plugin. From a basic scenario point of view, it is like this:

  • .tmpl()Render the template
  • .tmplItem()Find the template item
  • .template()Compile/Store the template $.template()方法,将一段Html编译为模板

The template itself is any HTML markup, along with any of a set of template tags which enable some very rich scenarios for creating data-driven UI. The current set of tags that are supported in jQuery templates are:

  • ${…}Evaluate fields or expression
  • {{each …}}…{{/each}}Iterate without creating template items
  • {{if …}}…{{else …}}…{{/if}}Conditional sections
  • {{html …}}Insert markup from data
  • {{tmpl …}}Composition, as template items
  • {{wrap …}}…{{/wrap}}Composition, plus incorporation of wrapped HTML
$.tmpl( "<li>${Name}</li>", { "Name" : "John Doe" }).appendTo( "#target" );
  • 第一个参数是html模板,里面可以包含html标签,变量(比如${Name}),逻辑(比如)等;
  • 第二个可选参数是数据,可以是JavaScript对象或者数组(其实JavaScript数组就是对象,而不像大多数语言那样,是一种更快的原生数据)。
<script id="pageTmpl" type="text/x-jquery-tmpl">




var pageTmpl = $('#pageTmpl').html();


var pageData;

pageData.value1 = ‘string 1’;

pageData.value2 = ‘string 2’;



Composition with jQuery Templates: Why and How

An example scenario: The invoice

Imagine that you need to display an invoice for a company that resells taxable items and also sells services. Ideally, the invoice line items for those separate “types” should be displayed with different markup. To explore a simple example of that, let’s create a template to render the invoice for a fictional web development company.

Whether retrieved from a server-side endpoint or embedded in the page during initial rendering, the underlying data for that invoice might be structured something like this:

var invoice = {
  invoiceItems: [
    { type: 'item', 
      part: '99Designs', description: '99 Designs Logo', 
      price: 450.00, qty: 1 },
    { type: 'service',
      service: 'Web development and testing', 
      price: 25000.00 },
    { type: 'item',
      part: 'LinodeMonthly', description: 'Monthly site hosting', 
      price: 40.00, qty: 12 }

Following from that data structure, our goal for the invoice’s markup might look something like this:

    <td>99 Designs Logo</td>
    <td colspan="2">Web development and testing</td>
    <td colspan="2">$25,000.00</td>
    <td>Monthly hosting at Linode</td>

Notice that the markup for service and item rows is structurally different, to better represent the underlying data. When that’s desirable, composing sub-templates is the way to go. As we’ll see next, the alternative is unappealing.


dynamically assign with jquery css top and left for an image thumb

The addElement function sets a variable by grabbing the element of which we will append a child node to.

<INPUT type="button" value="Add" onclick="add(document.forms[0].element.value)"/>

adding pixels to jquery .css() left property

For example, to add 150px:

$(this).css("left", "+=150")
// Gets the number of elements with class yourClass
var numItems = $('.yourclass').length

using img tag

function fnLoadImage_1() {
var imagePath = ""
document.getElementById('resultAreaID_1').innerHTML = "<img src="+imagePath +" onload='fnCallback_1()'>";
$(document).ready(function() {
document.getElementById('testCodeBtnID_1').onclick = function (){
function fnCallback_1(){
alert("Image loaded successfully.")

Using Image object

Load image using jQuery

Before running any script, make sure that you have empty image nodes in your html file.

set src attribute blank just before actually providing the image path.

function fnLoadImage_4() {
    $('#resultAreaID_4').attr("src", "")
    var imagePath = ""
    $('#resultAreaID_4').attr("src", imagePath)
// Called when image is loaded
function fnCallback_4() {
// Function called when DOM is ready
$(document).ready(function () {
    $('#resultAreaID_4').attr("src", "").load(fnCallback_4);
    document.getElementById('testCodeBtnID_4').onclick = function () {

 set as absolute

jQuery – Looped Slider Images From Folder

automatically read images from a directory and add the alt tag, link and caption using the image meta information.

//Relative path to yout image directory
$dirpath = "slideshow";
//Website URL to that same image directory
$dirURL = "";

$folder = opendir($dirpath);
$pic_types = array("jpg", "jpeg");
$alttag = "";
$websiteurl= "";
$caption = "";
$index = array();

//Loop through the images in the directory
while ($file = readdir ($folder)) {
  if(in_array(substr(strtolower($file), strrpos($file,".") + 1),$pic_types))
      $items[] = $file;            
//each time it loads it shuffles the images
for($i=0; $i<sizeof($items); $i++) {
  $picpath = $dirpath . "/" . $items[$i];
  $exif = exif_read_data($picpath, 'EXIF');
  $alttag = $exif['Title']; //alt tag
  $websiteurl= $exif['Subject']; //website url
  $caption = $exif['Comments']; //caption
  $title = $exif['Title']; //title
  $comments = $exif['Comments']; //comments

 $varimages = $varimages . "<li--><divcolor: rgb(0, 0, 255);">">";

//Build the html code based on the metadata
  if ($caption != "") {
    $caption =  "title='" . $caption  . "'";
    $alt = "alt='" . $caption  . "'";
  if ($alttag != "") {
    $alt =  "alt='" . $alttag . "'";
  if ($websiteurl != "") {
    $varimages =  $varimages . " <a href="$websiteurl"><img src="$picpath" $alt="" $caption="" height="254" width="625"></a>" ;
  } else {
  $varimages =  $varimages . " <img src="$picpath" $alt="" $caption="" height="254" width="625">";
  $alttag = "";
  $websiteurl= "";
  $caption = "";
  $varimages =  $varimages . "</div><divcolor: rgb(0, 0, 255);">">
          <p>$comments </p></div>";

echo $varimages;



屏幕宽度,自定义jquery element width,height

p img {
padding: 0;
max-width: 100%;

Firefox往往能正常解析max-width: 100%;这一句,自动限制图片显示大小,但IE不行。解决方法:在线编辑,在p img{}里再加一行:width: 450px;
450px是firefox里显示max-width: 100%;的最佳大小,就把它定义成这个了,刷新IE后就可以发现效果和firefox一样了。

  • $(window).width(); // returns width of browser viewport
  • $(document).width(); // returns width of HTML document

By utilizing jQuery’s “resize()” method, we can easily listen for when the user changes the width of their browser window.


jQuery Window Width Determined

jQuery .width() returns a numerical value only, i.e.325.  The value is in pixels.  However, .css(width) will return the number and units, i.e. 325px.   We want to use jQuery window width since we’ll test for numerical values later.

detect window/ browser size with jQuery and hide the certain element if the width is less then 900px

  • use CSS Media Queries to adapt pages style to various display widths and use em units and percentages and min-width and max-width in my CSS to get a proper flexible layout or how to check the user agent

Width Range Browser Window Screen Resolution
0px – 500px 1.13% 1.02%
501px – 800px 2.01% 1.06%
801px – 1000px 2.84% 0.07%
1001px – 1200px 14.91% 6.86%
1201px – 1400px 40.65% 35.57%
1401px – 1600px 17.38% 17.17%
1601px – 2000px 20.41% 34.34%
2000px+ 0.66% 3.91%

So where is mobile in all this? Despite reports of massive growth in mobile browsing, which I do not doubt, CSS Tricks has very little mobile traffic.

Let’s wrap it up with some quick hits:

  • The most popular screen resolution is 1680 x 1050 with almost 13% of visits having a monitor of that size.
  • Predictably, there is no one browser window size that is far above all others, but leading the pack is 1349 x 667 at 0.75% of visits.
  • The most popular screen resolution ratio is 16:10 with 46% of visits having that. Maybe because a lot of video is 16:9 and monitor makers wanted people to watch that but still have room for some OS chrome? 16:9 is next with 29%, 5:4 with 12%, and 4:3 with 8%.
  • All of those ratios are wider than tall. Turns out only 2% of visitors have screens that are taller than wide (or at least that report that way).
  • Actual browser windows also tend to be wider than tall, with only 3% of visits having dimensions that are taller than wide.
  • Average number of pixels per screen = 1,539,515
  • Average screen resolution = 1526 x 967
  • Average browser window size = 1366 x 784


“当你不创造东西时,你只会根据自己的感觉而不是能力去看待问题。” – WhyTheLuckyStiff
成功哲学很简单:Do Things, Tell People!


.con-text {
padding: 8px 10px;
background: red;
border: 1px solid #CCC;
color: blue;
如果我们需要多个这样类似的p,但又要求文本颜色不一样的话,会怎么办,重写多个类? .con-text1, .con-text2 … ?
span style=”white-space:pre;”> 显然太不现实,也太过冗余,所以或许我们需要用的面向对象中一个重要的思路–抽像公共接口。或许我们可以这么做:
.normal-text {
padding: 8px 10px;
background: red;
border: 1px solid #ccc;
.red {color: red}
.blue {color: blue}
<p class=”normal-text red“>test1</p>
<p class=”normal-text blue”>test2</p>
.normal-text {
padding: 8px 10px;
border: 1px solid #ccc;
.bg-red {background: red}
.blue {color: blue}
<p  class=”normal-text bg-red blue“>test</p>
.bg-red {background: red}
.blue {color: blue}
.pad-t8 {padding-top: 8px}
.pad-l10 {padding-left: 10px}
.clearfix:after {
content: “.”;
display: block;
height: 0;
clear: both;
visibility: hidden;
/* Hides from IE-mac \*/
.clearfix {zoom: 1;}
/* End hide from IE-mac */
3.可以为栅格化的布局样式做抽离, 如:col-a{width:..}, clo-b {width: ..}等等

构造函数/原型 的混合方式来构建JS

var slider = function () {
var init = function () {
init.protorype = {
pos : function () {
anim : function () {
auto : function () {
return init;
/* init */
new slider();

1)css并没有难懂的地方,关键在于积累。多去了解为什么要这么写css。比如几个很重要的css2.0中的属性,position,display,float,overflow 之类的,它们常用的值和应用场景为什么要这么用,这么去组合,多思考对于攻克布局有莫大的好处。

2)学javascript可以尝试从一些简单的可实现的东西开始,比如怎么操纵一个dom元素,改变它的各种东西,让它动起来。然后过渡到写组件。我这里建议一定开始要从学习原生的javascript语言开始。当你开始尝试写组件的时候,就一定要开始注意代码的结构了。养成好的编码习惯非常重要,会极大的推动后续的学习进度。所以这个阶段建议找 国内外用原生js代码编写的 优秀的,高代码质量的js组件做参考。 思考为什么别人要这么写,这么去组织代码


4)当过了第三阶段之后,我建议可以尝试着阅读国内外优秀的js底层基础库的源码,并尝试自己实现一套。不用奔着想“造轮子”有多少人用的想法。而是实现这个架构和其中的代码细节对于自己的学习非常重要。比如我自己也有一套粗糙的js基础库 ,但我并没打算将它应用出去,因为我它并没那么优秀,对我的意义在于实现它让我了解了国内外主流js基础框架的实现思路和大体架构。同时又是一份沉淀,当我某时想用某段代码时,直接找出来就能用。



this.$el .prototype .proxy

this.$el = $( ‘<div class=”gr-room”><div class=”gr-wall-main”><div class=”gr-floor”></div></div></div>‘ ).insertAfter( $itemsContainer );

  •  4 walls (or 1 if no support for 3dtransforms)
  • adjust the value of the perspective according to the value of the current window’s width

$(this.el) wraps an element with jQuery. So, if your view HTML was this:

<div id="myViewElement"></div>

…and this.el referenced that div, then $(this.el) would be the equivalent of retrieving it directly via jQuery: $('#myViewElement').

In JavaScript, the prototype is the mechanism which provides inheritance (as opposed to, say, classes). Example:String.prototype refers to the prototype object of Strings, which contains (among other things) methods which can be invoked on any String.

$('ul li').each(function()

This is far more simple to walk over a set of elements with the .each() function.

jQuery.proxy( function, context [, additionalArguments ] )

This method is most useful for attaching event handlers to an element where the context is pointing back to a different object. Additionally, jQuery makes sure that even if you bind the function returned from jQuery.proxy() it will still unbind the correct function if passed the original.

It allows us the ability to force a particular context when calling a method. In JavaScript, there can be times when it’s difficult to hold on to the this keyword. For example, when it’s bound to some event handler, this now refers to the target of the handler, rather than your desired object.

jquery append script to html element dynamically

The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend()).

<div class="container">
<div class="inner">Hello</div>
<div class="inner">Goodbye</div>
$(‘.inner’).append(‘<p>Test</p>’); // append()前面是要选择的对象后面是要在对象内插入的元素内容
<div class="container">
<div class="inner">
<div class="inner">

The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target:

  • With .append(), the selector expression preceding the method is the container into which the content is inserted.
  • With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.

$(‘<p>Test</p>’).appendTo(‘.inner’); //appendTo()前面是要插入的元素内容,而后面是要选择的对象

this.$navPrev = $( ‘<span class=”gr-prev”>prev</span>’ ).on( ‘click’, $.proxy( this.navigate, this, ‘prev’ ) );
this.$navNext = $( ‘<span class=”gr-next”>next</span>’ ).on( ‘click’, $.proxy( this.navigate, this, ‘next’ ) );
this.$nav = $( ‘<nav/>’ ).append( this.$navPrev, this.$navNext ).appendTo( $gallery );

// add caption container
this.$caption = $( ‘<div class=”gr-caption”><span class=”gr-caption-close”>x</span></div>’ ).appendTo( $gallery );
this.$caption.find( ‘’ ).on( ‘click’, $.proxy( this.hideDescription, this ) );


<span class=”gr-prev”>prev</span><span class=”gr-next”>next</span>

jQuery extend()

jQuery.extend( target [, object1 ] [, objectN ] )

Merge the contents of two or more objects together into the first object.


jquery.fn扩展imageloaded事件,应用技巧。以及data URI应用。

$(‘’,this).imagesLoaded(myFunction)   execute a callback when all images have loaded needed because .load() doesn’t work on cached images

Modified with a two-pass approach to changing image src. First, the proxy imagedata is set, which leads to the first callback being triggered, which resets imagedata to the original src, which fires the final,  user defined callback.

combine two different jQuery plugin

I’m pretty sure that the problem is that both scripts are calling two different jquery source files, but I can’t seem to figure it out how to change that.

How do I apply 2 widgets on the same div element. I tried something like <div id=”id1 id2″>

Lightbox + Loupe

what I want to do is to combine these two plugins in order to get the following feature: When i want to study an image/picture, I click on it to enlarge it (Lightbox2) and on the enlarged picture I can mouseover to get the “magnifying glass”(Loupe) in order to study it in more detail.

I have tried to implement the event Script from “Loupe” into the Lightbox.js plugin, with no success.



Just another site

Jing's Blog

Just another site

Start from here......







Just another site

Where On Earth Is Waldo?

A Project By Melanie Coles

the Serious Computer Vision Blog

A blog about computer vision and serious stuff

Cauthy's Blog

paper review...

Cornell Computer Vision Seminar Blog

Blog for CS 7670 - Special Topics in Computer Vision


Life through nerd-colored glasses

Luciana Haill

Brainwaves Augmenting Consciousness



Dr Paul Tennent

and the university of nottingham

turn off the lights, please

A bunch of random, thinned and stateless thoughts around the Web

John's Weblog

Just another weblog

I Am That I Am

Chasing tomorrow's sunrise.