By cllpse


2008-10-08 13:06:00 8 Comments

Syntax

Data Storage

Optimization

Miscellaneous

30 comments

@TM. 2009-05-21 12:05:51

Live Event Handlers

Set an event handler for any element that matches a selector, even if it gets added to the DOM after the initial page load:

$('button.someClass').live('click', someFunction);

This allows you to load content via ajax, or add them via javascript and have the event handlers get set up properly for those elements automatically.

Likewise, to stop the live event handling:

$('button.someClass').die('click', someFunction);

These live event handlers have a few limitations compared to regular events, but they work great for the majority of cases.

For more info see the jQuery Documentation.

UPDATE: live() and die() are deprecated in jQuery 1.7. See http://api.jquery.com/on/ and http://api.jquery.com/off/ for similar replacement functionality.

UPDATE2: live() has been long deprecated, even before jQuery 1.7. For versions jQuery 1.4.2+ before 1.7 use delegate() and undelegate(). The live() example ($('button.someClass').live('click', someFunction);) can be rewritten using delegate() like that: $(document).delegate('button.someClass', 'click', someFunction);.

@Nosredna 2009-05-28 18:34:29

Yeah, I love the new live stuff. Note that it only works starting with jQuery 1.3.

@Luke101 2009-11-18 01:28:07

+1..you have saved me alot of heart ache..I just happened to read your entry and while I was taking a break - trobleshooting why my event was not firing. Thanks

@Oskar Austegard 2010-10-14 03:06:48

for any other late-comers to this article, you may also want to look at delegate(): api.jquery.com/delegate Similar to live, but more efficient.

@nickytonline 2011-06-08 02:40:49

Just remember .live bubbles up to the body so that the bound live event can be fired. If something along the way cancels that event, the live event will not fire.

@daGrevis 2011-11-09 12:38:40

Didn't know about die(). Thanks!

@Johan 2012-01-03 13:58:54

live() and die() are deprecated methods since jQuery 1.7 released november 3rd. Replaced by on(), api.jquery.com/on and off(), api.jquery.com/off

@Nathan Long 2008-12-23 19:13:19

Save jQuery Objects in Variables for Reuse

Saving a jQuery object to a variable lets you reuse it without having to search back through the DOM to find it.

(As @Louis suggested, I now use $ to indicate that a variable holds a jQuery object.)

// Bad: searching the DOM multiple times for the same elements
$('div.foo').each...
$('div.foo').each...

// Better: saving that search for re-use
var $foos = $('div.foo');
$foos.each...
$foos.each...

As a more complex example, say you've got a list of foods in a store, and you want to show only the ones that match a user's criteria. You have a form with checkboxes, each one containing a criteria. The checkboxes have names like organic and lowfat, and the products have corresponding classes - .organic, etc.

var $allFoods, $matchingFoods;
$allFoods = $('div.food');

Now you can keep working with that jQuery object. Every time a checkbox is clicked (to check or uncheck), start from the master list of foods and filter down based on the checked boxes:

// Whenever a checkbox in the form is clicked (to check or uncheck)...
$someForm.find('input:checkbox').click(function(){

  // Start out assuming all foods should be showing
  // (in case a checkbox was just unchecked)
  var $matchingFoods = $allFoods;

  // Go through all the checked boxes and keep only the foods with
  // a matching class 
  this.closest('form').find("input:checked").each(function() {  
     $matchingFoods = $matchingFoods.filter("." + $(this).attr("name")); 
  });

  // Hide any foods that don't match the criteria
  $allFoods.not($matchingFoods).hide();
});

@Louis 2010-09-12 13:44:59

My naming convention is to have a $ in front. e.g. var $allItems = ...

@Nathan Long 2010-12-07 18:29:56

@Lavinski - I think the idea is that the $ indicates that this is a jQuery object, which would make it easier to visually differentiate from other variables.

@Nathan Long 2011-11-01 20:19:49

@Louis - I have since adopted your convention, and will update my answer accordingly. :)

@cllpse 2009-10-05 11:16:17

This one goes out to Kobi.

Consider the following snippet of code:

// hide all elements which contains the text "abc"
$("p").each(function ()
{
    var that = $(this);

    if (that.text().indexOf("abc") > -1) that.hide();
});    

Here's a shorthand... which is about twice as fast:

$("p.value:contains('abc')").hide();

@ngn 2011-07-20 23:23:19

Bind to an event and execute the event handler immediately:

$('selector').bind('change now', function () { // bind to two events: 'change' and 'now'
    // update other portions of the UI
}).trigger('now'); // 'now' is a custom event

This is like

function update() {
    // update other portions of the UI
}
$('selector').change(update);
update();

but without the need to create a separate named function.

@cllpse 2009-02-16 10:08:42

Syntactic shorthand-sugar-thing--Cache an object collection and execute commands on one line:

Instead of:

var jQueryCollection = $("");

jQueryCollection.command().command();

I do:

var jQueryCollection = $("").command().command();

A somewhat "real" use case could be something along these lines:

var cache = $("#container div.usehovereffect").mouseover(function ()
{
    cache.removeClass("hover").filter(this).addClass("hover");
});

@Sander Versluys 2009-07-09 11:51:22

it better to put the $(this) reference in a local variable, because you wil take a minor perfomance hit here, because it will take a little longer...

@cllpse 2009-07-15 07:26:59

In this case (no pun intended) I am only using "this" one time. No need for caching.

@gradbot 2011-04-30 16:38:03

A small tip. While it may not matter in this case it's always a bad idea to make extra changes to the DOM. Say for example the element you are hovering over already had the class "hover". You would be removing this class and re-adding it. You can get around that with $(this).siblings().removeClass("hover"). I know this sounds like such a small thing but every time you change the DOM another browser redraw may be triggered. Other possibilities include events attached to DOMAttrModified or the classes changing the height of the element which could fire other "resize" event listeners.

@gradbot 2011-04-30 16:47:17

If you want to use the cache and minimize DOM changes you can do this. cache.not(this).removeClass("hover")

@Randomblue 2011-09-02 01:14:24

@gradbot: I don't understand your last two comments. Could you expand?

@Stephen Burns 2011-04-20 02:27:02

The "ends with" element selector is great for ASP.NET web forms development because you don't need to worry about the prepended ctl00 silliness:

$("[id$='txtFirstName']");

As noted in the comments, this selector (as with any layer of abstraction) can be slow if used without care. Prefer to scope the selector to some containing element, e.g.,

$(".container [id$='txtFirstName']");

to reduce the number of required elements to traverse.

jQuery documentation

@cllpse 2011-04-20 08:19:38

You should probably note/warn that this type of selector is incredibly slow. Unless you're selecting on a subset, or a cached collection, this selector will traverse all elements in the DOM and run a regular expression on the ID property to determine a match.

@pyccki 2012-02-23 02:59:53

Stephen when it really bad, you can use this one, it searches entire id $("input[id*=txtFirstName]"); //* search "all" Most of the time I use ClientID $('#<%=txtFirstName.ClientId %>');

@OneNerd 2010-05-01 16:27:55

Asynchronous each() function

If you have really complex documents where running the jquery each() function locks up the browser during the iteration, and/or Internet Explorer pops up the 'do you want to continue running this script' message, this solution will save the day.

jQuery.forEach = function (in_array, in_pause_ms, in_callback)
{
    if (!in_array.length) return; // make sure array was sent

    var i = 0; // starting index

    bgEach(); // call the function

    function bgEach()
    {
        if (in_callback.call(in_array[i], i, in_array[i]) !== false)
        {
            i++; // move to next item

            if (i < in_array.length) setTimeout(bgEach, in_pause_ms);
        }
    }

    return in_array; // returns array
};


jQuery.fn.forEach = function (in_callback, in_optional_pause_ms)
{
    if (!in_optional_pause_ms) in_optional_pause_ms = 10; // default

    return jQuery.forEach(this, in_optional_pause_ms, in_callback); // run it
};


The first way you can use it is just like each():

$('your_selector').forEach( function() {} );

An optional 2nd parameter lets you specify the speed/delay in between iterations which may be useful for animations (the following example will wait 1 second in between iterations):

$('your_selector').forEach( function() {}, 1000 );

Remember that since this works asynchronously, you can't rely on the iterations to be complete before the next line of code, for example:

$('your_selector').forEach( function() {}, 500 );
// next lines of code will run before above code is complete


I wrote this for an internal project, and while I am sure it can be improved, it worked for what we needed, so hope some of you find it useful. Thanks -

@cllpse 2010-10-19 10:17:43

Access jQuery functions as you would an array

Add/remove a class based on a boolean...

function changeState(b)
{
    $("selector")[b ? "addClass" : "removeClass"]("name of the class");
}

Is the shorter version of...

function changeState(b)
{
    if (b)
    {
        $("selector").addClass("name of the class");
    }
    else
    {
        $("selector").removeClass("name of the class");
    }
}

Not that many use-cases for this. Never the less; I think it's neat :)


Update

Just in case you are not the comment-reading-type, ThiefMaster points out that the toggleClass accepts a boolean value, which determines if a class should be added or removed. So as far as my example code above goes, this would be the best approach...

$('selector').toggleClass('name_of_the_class', true/false);

@TM. 2010-10-19 15:13:30

This is neat, and has some interesting uses, but it isn't anything specific to jQuery at all... this is just something you can do on any JavaScript object.

@cllpse 2010-10-20 14:00:05

Thanks :) ... It's basic JavaScript; yeah. But I would argue that jQuery is JavaScript. I'm not claiming that this is jQuery-specific.

@ThiefMaster 2010-11-02 00:47:14

In this specific case you really want to use $('selector').toggleClass('name_of_the_class', b); though.

@cllpse 2011-03-23 19:30:43

HTML5 data attributes support, on steroids!

The data function has been mentioned before. With it, you are able to associate data with DOM elements.

Recently the jQuery team has added support for HTML5 custom data-* attributes. And as if that wasn't enough; they've force-fed the data function with steroids, which means that you are able to store complex objects in the form of JSON, directly in your markup.

The HTML:

<p data-xyz = '{"str": "hi there", "int": 2, "obj": { "arr": [1, 2, 3] } }' />


The JavaScript:

var data = $("p").data("xyz");

data.str // "hi there"
typeof data.str // "string"

data.int + 2 // 4
typeof data.int // "number"

data.obj.arr.join(" + ") + " = 6" // "1 + 2 + 3 = 6"
typeof data.obj.arr // "object" ... Gobbles! Errrghh!

@cllpse 2009-06-15 21:42:02

Remove elements from a collection and preserve chainability

Consider the following:

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>


$("li").filter(function()
{
    var text = $(this).text();

    // return true: keep current element in the collection
    if (text === "One" || text === "Two") return true;

    // return false: remove current element from the collection
    return false;
}).each(function ()
{
    // this will alert: "One" and "Two"       
    alert($(this).text());
});

The filter() function removes elements from the jQuery object. In this case: All li-elements not containing the text "One" or "Two" will be removed.

@DisgruntledGoat 2009-09-01 22:38:17

Isn't it simpler just to use "each" and move the margin change inside the switch?

@cllpse 2009-09-02 08:20:03

Updated my answer. Please let me know if I'm making myself clear(er)

@Cheeso 2009-12-15 19:37:02

Does this really REMOVE li elements? It seems to alert with a filtered list of elements.

@cllpse 2009-12-16 13:18:05

The filter function removes elements from the collection inside the jQuery object. It does not affect the DOM.

@Vincent 2010-05-26 18:40:13

In your filter function, you can simply write: return !!$(this).text().match(/One|Two/); ;)

@Oli 2008-10-08 13:11:42

I'm really not a fan of the $(document).ready(fn) shortcut. Sure it cuts down on the code but it also cuts way down on the readability of the code. When you see $(document).ready(...), you know what you're looking at. $(...) is used in far too many other ways to immediately make sense.

If you have multiple frameworks you can use jQuery.noConflict(); as you say, but you can also assign a different variable for it like this:

var $j = jQuery.noConflict();

$j("#myDiv").hide();

Very useful if you have several frameworks that can be boiled down to $x(...)-style calls.

@cllpse 2008-10-08 13:19:09

@Oli: About the document ready-shorthand; you have a point. But never the less: it is a tip/trick. One which I use in all my code purely because I think it "looks" better. A matter of personal preference, I guess :)

@JoeBloggs 2008-12-12 11:20:39

Every day I wade through pointless XML/XLS/XLST, sites written with far too many layers of abstraction, complex fail-over systems on sites that will never outgrow the humblest of servers... and still people complain about the difference between $(<string>) & $(<function>). Makes me want to cry :)

@luikore 2009-12-28 09:51:44

When I see $(function(){...}) I know what's going on. The more usual things should be shorter. That's why we turn frequently called code fragments into functions.

@Andreas Grech 2008-12-20 04:35:44

Creating an HTML Element and keeping a reference

var newDiv = $("<div />");

newDiv.attr("id", "myNewDiv").appendTo("body");

/* Now whenever I want to append the new div I created, 
   I can just reference it from the "newDiv" variable */


Checking if an element exists

if ($("#someDiv").length)
{
    // It exists...
}


Writing your own selectors

$.extend($.expr[":"], {
    over100pixels: function (e)
    {
        return $(e).height() > 100;
    }
});

$(".box:over100pixels").click(function ()
{
    alert("The element you clicked is over 100 pixels height");
});

@Hugoware 2008-12-23 17:18:44

Writing your own selectors is pretty slick

@Hugoware 2008-12-23 19:27:04

Also, if it's any help, you can actually do $("<div/>") and achieve the same thing as $("<div></div>")

@Pim Jager 2008-12-23 19:45:57

I love the new selector part, didn't know about that.

@Ben Blank 2008-12-23 21:21:29

Since I can't edit community wikis yet: Combine assignment and existence check with if ((var someDiv = $("#someDiv")).length) { /* do stuff with someDiv... */ }

@TM. 2008-12-23 23:32:01

Adding selectors: amazing! Wish I learned that a long time ago!

@Andreas Grech 2010-05-03 15:55:26

@Ben: The reason I avoid such idioms in JavaScript is because I don't want to give the illusion of someDiv having being scoped in the if statement, because it isn't; JavaScript only supports function scope

@Rixius 2010-07-06 19:14:33

Using self-executing anonymous functions in a method call such as .append() to iterate through something. I.E.:

$("<ul>").append((function ()
{
    var data = ["0", "1", "2", "3", "4", "5", "6"],
        output = $("<div>"),
        x = -1,
        y = data.length;

    while (++x < y) output.append("<li>" + info[x] + "</li>");

    return output.children();
}()));

I use this to iterate through things that would be large and uncomfortable to break out of my chaining to build.

@Shahin 2011-03-23 17:17:32

Access iFrame Elements Iframes aren’t the best solution to most problems, but when you do need to use one it’s very handy to know how to access the elements inside it with Javascript. jQuery’s contents() method makes this a breeze, enabling us to load the iframe’s DOM in one line like this:

$(function(){
    var iFrameDOM = $("iframe#someID").contents();
    //Now you can use <strong>find()</strong> to access any element in the iframe:

    iFrameDOM.find(".message").slideUp();
    //Slides up all elements classed 'message' in the iframe
});

source

@rbginge 2011-03-10 13:02:25

On a more fundamental and high-level note, you could try to emulate the basic selector mechanism of jQuery by writing your own little framework (it's simpler than it sounds). Not only will it improve your Javascript no end, it will also help you to understand just why jQuery's $("#elementId") is many times faster than $(".elementClass") and is also faster than $("element#elementId") (which is perhaps on the surface counter-intuitive).

This will also force you to learn about object oriented Javascript which will help you to organise your code in a more modular fashion, thereby avoiding the spaghetti code nature that heavy jQuery script blocks can take on.

@Ben Crouse 2008-10-10 12:39:58

I like declare a $this variable at the beginning of anonymous functions, so I know I can reference a jQueried this.

Like so:

$('a').each(function() {
    var $this = $(this);

    // Other code
});

@cllpse 2008-10-12 11:49:34

I use "that" instead :)

@JoeBloggs 2008-11-27 11:25:09

ROA: Yeah, that'll be the acid :) You can also use arguments.callee to enable an anonymous function to reference itself

@Mike Robinson 2009-06-26 15:19:49

Joe - just a heads up, callee will be going away with ECMAScript 5 and strict mode. See: ejohn.org/blog/ecmascript-5-strict-mode-json-and-more

@alex 2011-05-04 13:31:59

@Joe You could give it a name, just be wary of IE's quirks.

@LocalPCGuy 2012-01-20 02:49:07

Great example also of using a $ at the beginning of the variable name to indicate a jQuery object variable as compared to a standard variable. By adding that to the beginning of any variable that is caching a jQuery object, you immediately know by looking at it that you can perform jQuery functions on the variable. Makes the code much more readable immediately.

@adardesign 2011-02-20 18:51:24

Add a selector for elements above the fold

As a jQuery selector plugin

 $.extend($.expr[':'], {
 "aboveFold": function(a, i, m) {
   var container = m[3],
   var fold;
  if (typeof container === "undefined") {
     fold = $(window).height() + $(window).scrollTop();
  } else {
     if ($(container).length == 0 || $(container).offset().top == null) return false;
     fold = $(container).offset().top + $(container).height();
  }
  return fold >= $(a).offset().top;
 } 
});

Usage:

$("p:aboveFold").css({color:"red"});

Thx to scottymac

@cllpse 2011-02-10 20:41:45

A shameless plug... The jQuery template plug-in: implementing complex logic using render-functions

The new jQuery template plug-in is awesome. That being said, the double-curly brace template-tags are not exactly my cup of tea. In a more complex template the tags obscure the templates markup, and implementing logic past simple if/else statements is a pain.

After messing around with the plug-in for a few hours, my head began to hurt from trying to distinguish the markup in my template from the millions of double curly braces.

So I popped an aspirin and began work on an alternative

@LocalPCGuy 2012-01-20 02:47:49

Look at JSRender. I think the double-curly brace seems to be becoming a bit of a standard for templates in JavaScript templating.

@Ralph Holzmann 2010-12-03 18:16:37

Use filtering methods over pseudo selectors when possible so jQuery can use querySelectorAll (which is much faster than sizzle). Consider this selector:

$('.class:first')

The same selection can be made using:

$('.class').eq(0)

Which is must faster because the initial selection of '.class' is QSA compatible

@Ralph Holzmann 2011-10-11 16:52:26

@Nyuszika7H I think you're missing the point. The point is that QSA can't optimize most pseudo selectors, thus $('.class:eq(0)') would be slower than $('.class').eq(0).

@mshafrir 2009-02-02 20:24:56

On the core jQuery function, specify the context parameter in addition to the selector parameter. Specifying the context parameter allows jQuery to start from a deeper branch in the DOM, rather than from the DOM root. Given a large enough DOM, specifying the context parameter should translate to performance gains.

Example: Finds all inputs of type radio within the first form in the document.

$("input:radio", document.forms[0]);

Reference: http://docs.jquery.com/Core/jQuery#expressioncontext

@nyuszika7h 2011-02-15 16:07:14

A note: $(document.forms[0]).find('input:radio') does the same thing. If you look at the jQuery source, you'll see: if you pass a second parameter to $, it will actually call .find().

@daGrevis 2011-11-08 15:50:37

What about... $('form:first input:radio')?

@LocalPCGuy 2012-01-20 02:45:01

Paul Irish pointed out in paulirish.com/2009/perf (starting on slide 17) that doing this is "backwards" from a readability standpoint. As @Nyuszika7H pointed out, it uses .find() internally, and $(document.forms[0]).find('input:radio') is very easy to read, compared to putting the context in the initial selector.

@cllpse 2010-02-07 17:39:55

Defining properties at element creation

In jQuery 1.4 you can use an object literal to define properties when you create an element:

var e = $("<a />", { href: "#", class: "a-class another-class", title: "..." });

... You can even add styles:

$("<a />", {
    ...
    css: {
        color: "#FF0000",
        display: "block"
    }
});

Here's a link to the documentation.

@egyamado 2009-05-28 20:00:13

Speaking of Tips and Tricks and as well some tutorials. I found these series of tutorials (“jQuery for Absolute Beginners” Video Series) by Jeffery Way are VERY HELPFUL.

It targets those developers who are new to jQuery. He shows how to create many cool stuff with jQuery, like animation, Creating and Removing Elements and more...

I learned a lot from it. He shows how it's easy to use jQuery. Now I love it and i can read and understand any jQuery script even if it's complex.

Here is one example I like "Resizing Text"

1- jQuery...

<script language="javascript" type="text/javascript">
    $(function() {
        $('a').click(function() {
            var originalSize = $('p').css('font-size'); // get the font size 
            var number = parseFloat(originalSize, 10); // that method will chop off any integer from the specified variable "originalSize"
            var unitOfMeasure = originalSize.slice(-2);// store the unit of measure, Pixle or Inch

            $('p').css('font-size', number / 1.2 + unitOfMeasure);
            if(this.id == 'larger'){$('p').css('font-size', number * 1.2 + unitOfMeasure);}// figure out which element is triggered
         });        
     });
</script>

2- CSS Styling...

<style type="text/css" >
body{ margin-left:300px;text-align:center; width:700px; background-color:#666666;}
.box {width:500px; text-align:justify; padding:5px; font-family:verdana; font-size:11px; color:#0033FF; background-color:#FFFFCC;}
</style>

2- HTML...

<div class="box">
    <a href="#" id="larger">Larger</a> | 
    <a href="#" id="Smaller">Smaller</a>
    <p>
    In today’s video tutorial, I’ll show you how to resize text every time an associated anchor tag is clicked. We’ll be examining the “slice”, “parseFloat”, and “CSS” Javascript/jQuery methods. 
    </p>
</div>

Highly recommend these tutorials...

http://blog.themeforest.net/screencasts/jquery-for-absolute-beginners-video-series/

@adam 2010-07-06 20:01:27

Increment Row Index in name

Here is a neat way to increment a row index of a cloned input element if your input element name contains a row index like '0_row':

$(this).attr('name', $(this).attr('name').replace(/^\d+/, function(n){ return ++n; }));

The cloned element's name will now be '1_row'

@Filip Dupanović 2009-02-02 20:35:41

Ooooh, let's not forget jQuery metadata! The data() function is great, but it has to be populated via jQuery calls.

Instead of breaking W3C compliance with custom element attributes such as:

<input 
  name="email" 
  validation="required" 
  validate="email" 
  minLength="7" 
  maxLength="30"/> 

Use metadata instead:

<input 
  name="email" 
  class="validation {validate: email, minLength: 2, maxLength: 50}" />

<script>
    jQuery('*[class=validation]').each(function () {
        var metadata = $(this).metadata();
        // etc.
    });
</script>

@Oskar Austegard 2010-10-14 03:05:22

html5 data attributes make this less of an issue; there is discussion afoot on bringing html5 data attribute inline with jquery's data() function: forum.jquery.com/topic/…

@nickf 2010-10-16 21:07:37

@Oskar - yep this has been implemented in jQuery 1.4.3 -- data-* attributes are automatically available via calls to .data()

@Kenneth J 2010-05-05 23:27:20

Use .stop(true,true) when triggering an animation prevents it from repeating the animation. This is especially helpful for rollover animations.

$("#someElement").hover(function(){
    $("div.desc", this).stop(true,true).fadeIn();
},function(){
    $("div.desc", this).fadeOut();
});

@Vivin Paliath 2010-02-07 21:04:21

Changing the type of an input element

I ran into this issue when I was trying to change the type of an input element already attached to the DOM. You have to clone the existing element, insert it before the old element, and then delete the old element. Otherwise it doesn't work:

var oldButton = jQuery("#Submit");
var newButton = oldButton.clone();

newButton.attr("type", "button");
newButton.attr("id", "newSubmit");
newButton.insertBefore(oldButton);
oldButton.remove();
newButton.attr("id", "Submit");

@cllpse 2010-02-07 20:10:07

Line-breaks and chainability

When chaining multiple calls on collections...

$("a").hide().addClass().fadeIn().hide();

You can increase readability with linebreaks. Like this:

$("a")
.hide()
.addClass()
.fadeIn()
.hide();

@nyuszika7h 2011-02-15 16:20:18

In this case, the first is more readable, but yeah, there are some cases when line breaks increase readibility.

@cllpse 2010-02-07 20:07:40

Shorthand for the ready-event

The explicit and verbose way:

$(document).ready(function ()
{
    // ...
});

The shorthand:

$(function ()
{
    // ...
});

@cllpse 2010-02-07 20:04:18

No-conflict mode

jQuery.noConflict();

"Run this function to give control of the $ variable back to whichever library first implemented it. This helps to make sure that jQuery doesn't conflict with the $ object of other libraries.

By using this function, you will only be able to access jQuery using the jQuery variable. For example, where you used to do $("div p"), you now must do jQuery("div p")".

@Tebo 2009-11-20 15:38:59

Update:

Just include this script on the site and you’ll get a Firebug console that pops up for debugging in any browser. Not quite as full featured but it’s still pretty helpful! Remember to remove it when you are done.

<script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>

Check out this link:

From CSS Tricks

Update: I found something new; its the the JQuery Hotbox.

JQuery Hotbox

Google hosts several JavaScript libraries on Google Code. Loading it from there saves bandwidth and it loads quick cos it has already been cached.

<script src="http://www.google.com/jsapi"></script>  
<script type="text/javascript">  

    // Load jQuery  
    google.load("jquery", "1.2.6");  

    google.setOnLoadCallback(function() {  
        // Your code goes here.  
    });  

</script>

Or

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>

You can also use this to tell when an image is fully loaded.

$('#myImage').attr('src', 'image.jpg').load(function() {  
    alert('Image Loaded');  
});

The "console.info" of firebug, which you can use to dump messages and variables to the screen without having to use alert boxes. "console.time" allows you to easily set up a timer to wrap a bunch of code and see how long it takes.

console.time('create list');

for (i = 0; i < 1000; i++) {
    var myList = $('.myList');
    myList.append('This is list item ' + i);
}

console.timeEnd('create list');

@Alireza Eliaderani 2009-11-28 15:33:30

ppl in Iran can't see web pages loaded with google api. in fact google has restrict Iranians to access google code. so -1

@Tebo 2009-12-28 09:33:07

I just found out you can use firebug in any browser. That's awesome.

Related Questions

Sponsored Content

36 Answered Questions

[SOLVED] Add table row in jQuery

36 Answered Questions

[SOLVED] $(document).ready equivalent without jQuery

  • 2009-04-28 21:51:11
  • FlySwat
  • 996030 View
  • 1952 Score
  • 36 Answer
  • Tags:   javascript jquery

18 Answered Questions

[SOLVED] Disable/enable an input with jQuery?

30 Answered Questions

[SOLVED] jQuery scroll to element

41 Answered Questions

[SOLVED] Setting "checked" for a checkbox with jQuery?

56 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

65 Answered Questions

[SOLVED] How do I check whether a checkbox is checked in jQuery?

27 Answered Questions

[SOLVED] How can I refresh a page with jQuery?

41 Answered Questions

[SOLVED] Is there an "exists" function for jQuery?

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 734267 View
  • 2703 Score
  • 41 Answer
  • Tags:   javascript jquery

Sponsored Content