William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

Tag Archives: jquery

jQuery.extend & callback

jQuery.extend & callback

Here is my simple example to use jQuery.extend to add params and callback function.

jQuery.fn.threeColumns = function(params, callback) {
  var opts = {
    fsize_step: 2,
    //will use for element.css(opts.adjust_box());
    adjust_box: function() {
      return {
        'margin': '20px',
        'padding': '20px',
        'height': 'auto'
  jQuery.extend(opts, params);

  if(typeof opts.adjust_box === 'function') {

$('div.container').threeColumns({a:'b'}, function(params){

//Will display:
Object { margin="20px", padding="20px", height="auto"}
Object { fsize_step=2, a="b", adjust_box=function()}

Some JS examples

Some JS examples

Here are some of my JS/jQuery examples for quick retrieving:

//1. set _debug flag to auto switch log future in different envs:
_debug: /(williamjiang|localhost)/i.test(document.location.hostname),

 .bind("click.tree", function(event) {
   if ( this == event.target )
  }).add( $("a", this) ).hoverClass();

branches.each(function(i, e) {
  data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;

  .css('background-color', 'red');
//3.on(), off() 
var switchListHandler=function(e){
    if (typeof (e) == "undefined")
        e = window.event;
    if (typeof (e) == "undefined")
        return false;
    var srcEle = e.srcElement;
    if (!srcEle) srcEle = e.target;
    if(srcEle.tagName.toUpperCase()=='A') {...}    	

$(document).on('click', 'body', CountList.switchListHandler);

$(document).off('click', 'body', CountList.switchListHandler);

jQuery: terminate an event and apply for a new event

jQuery: terminate an event and apply for a new event: stop(true,true)

How to terminate a jQuery event immediately, and apply for a new event? It is better to use the interact function stop(true,true).
stop(true, true) is helpful to stop an running event on certain DOM element, and apply for a new event.
e.g.: stop a slideUp() event and apply a slideDown event, like this:

var mouseHandler = function (e) {
    $.debug('<mouseHandler>, e.type=' + e.type);
    $('div#list_popup').stop(true, true).slideDown('slow');
    return false;
$('div.list').one('mouseenter mouseleave', mouseHandler);

In this way, it will change slideUp() to slideDown() immediately when the ‘mouseenter’ or ‘mouseleave’ are triggered.

Images process: jQuery works with complex pngs

jQuery Photoshop UI application

I wrote a jQuery application which works with jQuery, Photoshop png files, and some CSS, and put it in my github cyberspace:



  • png image location with position relative and absolutive.
  • jQuery validation and AJAX.
  • jQuery UI and twitter bootstrap.
  • HTML <map>, <area>

Due to time reason, it is not perfect, still has some bugs need fix, and codes optimize; However, it is a good example to refer for image processing with jQuery.

jQuery select selector

jQuery select selector

Here I list get/set jQuery <Select> selector’s Text and Value:

  //add 'onChange' event for Select
  //get select's Text
  var checkText=$("#select_id").find("option:selected").text();
  //get select'sValue
  var checkValue=$("#select_id").val(); 
  //get select's index
  var checkIndex=$("#select_id ").get(0).selectedIndex;
  //get select's max index
  var maxIndex=$("#select_id option:last").attr("index"); 
  $("#select_id ").get(0).selectedIndex=1;
  $("#select_id ").val(4); 
  $("#select_id option[text='jQuery']").attr("selected", true); 
  //append a Option
  $("#select_id").append("<option value='Value'>Text</option>");
  //unshift a Option
  $("#select_id").prepend("<option value='0'>Select</option>"); 
  //push a option
  $("#select_id option:last").remove(); 
  //shift a option
  $("#select_id option[index='0']").remove(); 
  //remove a option (val()=3)
  $("#select_id option[value='3']").remove();
  //remove a option (text()='4')
  $("#select_id option[text='4']").remove();

jQuery Trigger example

jQuery Trigger example

Suppose we have a popup window in a webpage. In the popup window, there is a ‘link’ and a ‘input button’ to do the same thing: close the window, like this:

<a href="#" class="modal-close"></a>
// and:
<input type="button" value="Close" />

We can use jQuery ‘trigger‘ to simplify the codes:

//1. for the first, define the event.
 $('.modal-window').fadeOut(200, function(){
 return false;
//2. for the second, just trigger the first event.
$("input[value=Close]").click(function() {

This make the codes simple and easy to maintain.

Use ‘input:checkbox’ instead of ‘:checkbox’

Sometimes we use the following to process chechbox:


A better option is:


:checkbox is the same as *:checkbox and this means jQuery will execute “checkbox” == emlement.type for EVERY element in the DOM – pretty slow stuff.

jQuery: jqtransform

Swith theme: using simple jqtransform

Jqtransform is a jQuery styling plugin which allows you to skin form elements:

It is very easy to use, and with good effect. It by default changes all the elements type and outlook such as submit, reset, input buttons, and removes all the events on these elements.

However, I don’t want to replace some <input> buttons, such as close button, coz there is default event on it. e.g. a close button has a ‘click’ event:

<input type="button" value="close" onClick="$('#div_search_2', window.parent.document).hide(); $('#div_search_1', window.parent.document).show();" />

If using jqtransform, it will replace the ‘close‘ button like this:

<button id="" name="" type="button" class="jqTransformButton"><span><span>Close</span></span></button>

It is not exactly I want, because it deletes its original ‘click’ event.
To make ‘close‘ button work properly, I have to modify the source codes of jqtransform.js. By doing slight changes, it works:

1. orginal:
$('input:submit, input:reset, input[type="button"]', this).jqTransInputButton();  
2. change to:
$('input:submit, input:reset', this).jqTransInputButton();

This will igore all the input with type=”button” inside this form.

jQuery: Difference between .html().length and .length

in jQuery, it is very common to do the following 2 judges:

  1. Does the element exists?
    e.g., if a <div> exists, then add message to it; if not, create it then add message. In such case, use $(E).length.
  2. Does the element include something or empty?
    e.g., there is a <div>, how to know this div includes elements, html or just empty? In such case, use $(E).html().length.

The 2 judges are different, they are used in different case.

In case 1:

//if exist?  use $(element).length.
$('#divid').hover(function() {
 if($('#msg').length) {
 else {
  $('<span id="msg">some messages...</span>').appendTo('#divid');
}, function() {
 if($('#msg').length && $('#msg').is(':visible')) {

In case 2:

//Does element empty or include html?
if($("#divid").html().length==0) {

We can always use the following simple way to check:

var t = $(the_element);

jQuery examples summary 5

Continue the summary.

1. delegate( selector, events )
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

$("table").delegate("td", "hover", function(){
 $("td", this).live("hover", function(){
$("body").delegate("p", "click", function(){
 $(this).after("<p>Another paragraph!</p>");
$("body").delegate("a", "click", function(event){
jQuery('#mydiv').delegate('#mydiv > p', 'click', function() { 

2. event.target
The DOM element that initiated the event.

$("body").click(function(event) {
  $("#log").html("clicked: " + event.target.nodeName);
function handler(event) {
  var $target = $(event.target);
  if( $target.is("li") ) {

3. live( eventType, handler )
.live() is my favorite. It is very powerful. However, it may occur performance issue, so use it when have to.
Attach a handler to the event for all elements which match the current selector, now and in the future.

 click: function(){// do something on click},
 mouseover: function() {// do something on mouseover }
$("p").live("myCustomEvent", function(e, myName, myValue) {
 $(this).text("Hi there!");
 $("span").stop().css("opacity", 1)
   .text("myName = " + myName)
 $("button").click(function () {

$("p").live("click", function(){
 $(this).after("<p>Another paragraph!</p>");
 "mouseover": function() {
 "mouseout": function() {

Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will always propagate to the element to which they are delegated; event handlers on any elements below it will already have been executed by the time the delegated event handler is called.

To cancel only the default action by using the preventDefault method.

$("a").live("click", function(event){

4.trigger( eventType, extraParameters )
Execute all handlers and behaviours attached to the matched elements for the given event type. Using .trigger(‘click’) will not trigger the native click event. To simulate a default click, you can bind a click handler like so:

$('#someLink').bind('click', function() {
  window.location.href = this.href;
  return false;
$('input.mycheckbox').click(function() {
  if (this.checked) {

jQuery examples summary 4

Continue the summary, the examples are main from http://api.jquery.com/.

Continue the jQuery examples summary

//1. clone( [ withDataAndEvents ] )
Create a deep copy of the set of matched elements.


//2. fadeOut( [ duration ], [ callback ] )
Hide the matched elements by fading them to transparent.

//3. empty()
Remove all child nodes of the set of matched elements from the DOM. $(‘.hello’).empty();

//4. remove( [ selector ] )
Remove the set of matched elements from the DOM.
Similar to .empty(), the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

$("button").click(function () {
$("select#mySelect option[value='option1']").remove();
$("select#mySelect option[selected='true']").remove();
$('#mySelect :selected').remove();

About empty() and remove():

Due to the way jQuery handles remove vs empty, empty is thousands of times faster, at least in this situation.
So do this:


…instead of this:


Using empty() before remove() is much faster and safer.