case
ADM Blog
4May/110

jQuery.quickEach

With jQuery, when you need to iterate all elements with a specific class for example, you use the each() method and inside the callback function you must convert the DOM element you receive as this to a jQuery object in order to access it's jQuery specific methods: $(this)
This is not such a big issue but if you have a lot of items and/or do this often, then times ads up. It would be a blast to have the this object directly as a jQuery instance. So here's a $ little plugin that does exactly that

Source website:
http://jsperf.com/jquery-each-vs-quickeach

The code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
jQuery.fn.quickEach = (function() {
  var jq = jQuery([1]);
  return function(c) {
   var i = -1,
       el, len = this.length;
   try {
    while (++i < len && (el = jq[0] = this[i]) && c.call(jq, i, el) !== false);
   } catch (e) {
    delete jq[0];
    throw e;
   }
   delete jq[0];
   return this;
  };
 }());

If you run the test on that page, on most browsers you'll see that quickEach() is about 80% faster than native each()

30Mar/110

For Javascript devs

If you write Javascript apps you may want to dynamically add some HTML here and there and having HTML strings that need concatenation with different variables is bad and ugly at the same time. So here is a little nugget you might find useful.

1
2
3
4
5
    // standard style
    x = '<div class="' + classnames + '" rel="' + somevar + '" id="' + othervar + '">' + content + '</div>';
 
    // html tag style
    x = htmlTag('div', {class:classname, rel:somevar, id:othervar}, content);

Usage

htmlTag(tagName [, attributes [, content]])
or
htmlTag(tagName [, content [, attributes]])

The function can be called with one, two or three arguments. Beside the first one which is the name of the tag (string), the other two are optional and can be placed in whatever order you like.
For img tags, the content argument is set as src attribute or as value attribute for input tags if the attributes argument doesn't specify otherwise

attributes argument must be an object with key:value pairs and will be expanded as attributes of the tag
content argument is a string or number

1
2
3
4
5
6
7
8
9
10
11
12
13
    var classname = 'test', somevar = 2, id = 'mydiv', content = 'hello';
 
    htmlTag('div', {class:classname, rel:somevar, id:othervar}, content);
    htmlTag('div', content, {class:classname, rel:somevar, id:othervar});
    // will both return <div class='test' rel='2' id='mydiv'>hello</div>
 
    htmlTag('img', content)
    // <img src='hello' />
    htmlTag('img', {src:'myImage.jpg'}, content)
    // <img src='myImage.jpg' /> content is discarded and attributes src is used as source
 
    htmlTag('input', {type:'text', name:id}, content)
    // <input type="text" name="mydiv" value="hello" />

The code

1
2
3
4
5
6
7
8
9
10
11
function htmlTag(type) {
    var r="< "+type,o={},v='',x=0,a=arguments;
    a.length==3&&(((x=typeof a[1]=='object')||1)&&((o=a[-~!x]||{})&&(v=a[-~x]||'')))||a.length==2&&(typeof a[1]=='object'&&(o=a[1]||{})||(v=a[1]||''));
    for(var i in o)r+=" "+i+"='"+o[i]+"'";
    (type=='img'||type=='br'||type=='input')&&((!o.src&&v)&&((type=='img'&&(r+=" src='"+v+"' />"))||(type=='input'&&(r+=" value='"+v+"' />")))||(r+=' />'))||(r+=">"+v+"< "+"/"+type+">");
    return r;
}
 
function queryTag(type) {
     return $(htmlTag.apply(this, arguments))
}

queryTag function just wraps the newly created html in a jQuery object so you can have something like this

1
2
3
4
5
     $("#menu").append(
             queryTag('div', {class:'menuItem'}, 'Click me').click(function() {
                      alert('clicked');
             })
      )
28Sep/100

Parse XML in JavaScript with jQuery

Yes, you can do it with XMLDOM and all the other ways out there, but why not use the power of jQuery ?
Like so:

1
2
3
4
5
6
7
   <root>
      <items>
          <item name="first" id="1">Content 1</item>
          <item name="second" id="2">Content 2</item>
      </items>
      <other atribute="true" />
    </root>
1
2
3
4
   var xml = '<root ......';
   var obj = $(xml);
   // and now you can use jquery selectors to get what you want
   $("item[name=second]", obj).attr('id'); // 2

11Aug/100

On typing finished jQuery plugin

If you are developing a form and you require certain validations; check if username is available or not for example - the way to do that is to listen for the change/focusout DOM events. You can also check it on every keypress but if the validation does some expensive checking in the background that is out of the question. So here is a really small jQuery plugin that does tell you when a user finished typing inside a text box. The way it does it is to compute the speed the user is typing with and when a delay longer than twice the speed average occurs, the event is triggered and your validation function is called. Simple enough.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(document).ready(function () {
  $.fn.onTypeFinished = function(func) {
     var T = undefined, S = 0, D = 1000;
     $(this).bind("keypress", onKeyPress).bind("focusout", onTimeOut);
     function onKeyPress() {
        clearTimeout(T);
        if (S == 0) { S = new Date().getTime(); D = 1000; T = setTimeout(onTimeOut, 1000); return; }
        var t = new Date().getTime();
        D = (D + (t - S)) / 2; S = t; T = setTimeout(onTimeOut, D * 2);
     }
 
      function onTimeOut() {
           func.apply(); S = 0;
      }
      return this;
   };
});

The way to use it:

1
$("input[name='username']").onTypeFinished(myValidationFunction)

And here is a small demo: