Interesting jQuery() Function Signature

The jQuery() function is a little strange. Most people write $() instead of jQuery() (myself included) – slightly strange when you first start working with jQuery – what’s a little more unusual is the amount of signatures $ has:

// very common usage:
$(function(){
  // dom ready
});
 
// make a div and add it to the body
$("<div/>").appendTo("body");
 
// run a selector on a string (gives us back) [<p>​there​</p>​]
$("p", "<div>hello<p>there</p></div>");
 
// very standard usage...
// css selectors - returns a set of elements made up of all the divs in the document
$("div")
 
// etc... I counted 10 different signatures in the jQuery docs.

Turns out there was one that I didn’t know about – I read about it in this article 5 Things You Might Not Know About jQuery. When you create an element on the fly there is a second argument that is a map of methods and attributes. So you can easily initialize all aspects of an element that you’d like to create:

$("<div/>",{
  css: {position : "absolute",
        cursor : "pointer",
        left : 80,
        top : 100,
        width : 60,
        height : 50,
        color : "white",
        padding : 5,
        font: "12px sans-serif",
        border : "1px solid white",
        backgroundColor : "#827658"},
  click: function(){
    var size = parseInt(Math.random() * 100 + 60);
    $(this).animate({width:size, height:size});         
  },
  id : "blueBox",
  className : "shady",
  text : "Click Here"
}).appendTo("body");

The above creates this:

There is a little css just to illustrate that you can associate an element with a class:

.shady{
        /* css3 - not browser friendly */
        -webkit-box-shadow : 0px 0px 50px rgba(0,0,0,0.5); 
        -moz-box-shadow : 0px 0px 50px rgba(0,0,0,0.5); 
        box-shadow : 0px 0px 50px rgba(0,0,0,0.5); 
}


 
 
 

2 Responses to “Interesting jQuery() Function Signature”

  1. devu
    23. February 2011 um 08:36

    Interesting, as well as the fact, that this little nice effect is taking 40% (Fire Fox) 20%(chrome) of my 4 core processor.

  2. Zevan
    23. February 2011 um 08:41

    That IS interesting could you screenshot your system profiler? I’m curious…. because I don’t get those kind of results at all no my macbook pro laptop.

    Recently used this technique on an iphone web app – worked great on safari mobile with a whole bunch of divs :/

Leave a Reply

Spam protection by WP Captcha-Free