You are on page 1of 11

***********************************************************************************

*****************************************
How to find an element's dimension or width or height including padding, margin &
border?
Use outerWidth and outerHeight. They include the border and padding by default.
They will include the margin if the first argument of the function is true.

***********************************************************************************
*****************************************
$.extend:
a) Merge 2 or more objects into the target object and return target:
EX: $.extend(targ, json1, json2);

b) Add a global function to jQuery. This happens when target is omitted:


EX: $.extend(
{
jQueryGlobalFn: function() {alert("jQuery global function!!!!!!");}
}
);
$.jQueryGlobalFn();

***********************************************************************************
*****************************************
How to construct query params for an url from json?
var params = { width:1680, height:1050 };
var str = $.param(params); // str is "width=1680&height=1050"

$.trim(" abcd ") returns "abcd".

***********************************************************************************
*****************************************
How to select all elements in a page using jQuery?
$("*").css("border", "2px dotted red");

***********************************************************************************
*****************************************
The resize() function is called whenever the browser size is changed. This event
can be only used with $(window).
$(window).resize(function(){ $('#message).text('window is resized to ' + $
(window).width() + x' + $(window).height()); });

Resize function is called mulitple times in IE. Also, width or height calculation
within resize function might give wrong value.
To fix these issues, use timer:
function doWindowResize()
{}
var resizeTimeoutId;
function onWindowResize()
{
window.clearTimeout(resizeTimeoutId);
resizeTimeoutId = window.setTimeout(doWindowResize, 10);
}
$(window).resize(onWindowResize);

***********************************************************************************
*****************************************
What is $ in jQuery?
jQuery uses "$" as a shortcut for "jQuery".
$("#id") and jQuery("#id") are the same.
What is jQuery.noConflict()?
To avoid conflict with other libraries that have used $, jQuery provides
jQuery.noConflict() function.
When noConflict() is called, the control of the $ variable goes back to the other
library that first implemented it.
Once noConflict() is called, $('div.someClass') wouldn't work anymore, instead use
jQuery('div.someClass').

***********************************************************************************
*****************************************
What does $.fn mean?
The fn property is just an alias to the prototype property.
assert(jQuery.fn === jQuery.prototype);

$.fn is used so that extending a class defined inside anonymous function is


possible. Because jQuery is defined within an anonymous function.

EX:
(
function()
{
var foo = function(arg)
{
// ensure to use the "new" operator
if (!(this instanceof foo))
{
return new foo(arg);
}

this.myArg = arg;
};

// create "fn" alias to "prototype" property


foo.fn = foo.prototype = {
init: function () {/*...*/}
};

// expose the library


window.foo = foo;
}
)();

// Extension:
foo.fn.myPlugin = function()
{
alert(this.myArg);
return this; // return "this" for chainability
};

foo("bar").myPlugin(); // alerts "bar"


Use $.extend() to achieve this.

***********************************************************************************
*****************************************
Name 4 different values you can pass to the jQuery method.
Selector (string), HTML (string), Callback (function), HTMLElement, object, array,
element array, jQuery Object etc.
***********************************************************************************
*****************************************
createDelegate functionality using proxy():

function A() {this.idx = 10;}


A.prototype.getIdx = fucntion()
{
return this.idx; /* this refers A object, not dom */
};

var aObj = new A();

$('#test').click($.proxy(aObj.getIdx, aObj));

***********************************************************************************
*****************************************
$.grep filters an array by leaving out any items that don't satisfy given
condition.
For example, if we have an array of the numbers 1-10, and want to filter out any
values that are below 5, we can do:

var nums = '1,2,3,4,5,6,7,8,9,10'.split(',');


nums = $.grep(nums, function(num, index) {
// num = the current value for the item in the array
// index = the index of the item in the array
return num > 5; // returns a boolean
});

console.log(nums) // 6,7,8,9,10

***********************************************************************************
*****************************************
Set, get & remove data on html elements:
$('#container').data({ myOtherKey : 'myOtherValue', year : 2010 });
$('#container').data('myOtherKey'); // returns 'myOtherValue'
$('#container').removeData('myOtherKey');

***********************************************************************************
*****************************************
To get a specific element within a set of elements, pass the index of the element
to the eq() method.
var ps = $('p');
ps.eq(1).addClass('emphasis');
$('p:eq(1)').addClass('emphasis');

How to get DOM object from jQuery object?


.get() and .eq() both return a single "element" from a jQuery object array, but
they return the single element in different forms.
.eq() returns it as a jQuery object.
.get() returns a raw DOM element.

ps[0] returns first item in array.

$('h2').get(0) === $('h2').eq(0)[0] //true


$( $('h2').get(0) ) === $('h2').eq(0) //true

***********************************************************************************
*****************************************
How to get jQuery object from DOM object? var jqObj = $(domElement);
***********************************************************************************
*****************************************
To take siblings use $("#id1").siblings();

***********************************************************************************
*****************************************
How to remove css or style?
$("#id1").css("height", "");

***********************************************************************************
*****************************************
insertAfter() inserts given html after specifed element.
Sample:
<div class"samp"></div>

$('<p>Test</p>').insertAfter('.samp');

Now:
<div class"samp"></div>
<p>Test</p>

We can also use


$('.samp').after('<p>Test</p>');

insertBefore or before

***********************************************************************************
*****************************************
Append element:
$('body').append('<div id="progress">Loading...</div>');
append() adds given html content as last child of given parent. Use prepend() to
add as first child.

Remove element:
$('#progress').remove();
This method will remove all the jQuery data associated with the matched element.
detach() method is same as .remove() method except that the .detach() method
doesn't remove jQuery data associated with the matched elements.
empty() method removes not only child (and other descendant) elements, but also any
text within the set of matched elements.

Move element:
$('#id2').detach().appendTo($("#id1")); // Moves id2 from its current position and
adds as child of id1.
$('#id2').detach().insertBefore($("#id1")); // Moves id2 from its current position
and adds (as sibling) before id1.

***********************************************************************************
*****************************************
Select elements or tags by partial attribute values or selector?
$("div[id^='view_design']").attr('class', "divViewDesigns"); // Selects divs whose
id start with view_design.

$("[id$='_form']").hide(); // Select elements whose id ends with _form.


$("[id*='_form']").hide(); // Select elements whose id contains the string _form.

$("input[type!='hidden']");
How to do partial attribute values or selector within selector chain?
$("#deviceObjectAssignedTable i[class^='aclpermission-r']");

How to escape special characters in selector?


An element's id can have colon & period. How to select those elements?
$("#some:id"); // Does not work
$("#some\\:id"); // Works!
$("#some.id"); // Does not work
$("#some\\.id"); // Works!

function escapeSelector(str)
{
return (str ?
str.replace(/([ #;?%&,.+*~\':"!^$[\]()=>|\/@])/g,'\\\\$1') :
str);
}

***********************************************************************************
*****************************************
: in jQuery indicates a pseudo-class.
jQuery visible selector:
$("div:visible").css("width", "100px"); // Select divs that occupy some space
[width or height > 0]

$(ele).is(some_condition) checks whether ele satisfies given condition. EX:


$(ele).is(".cls1"); /* does ele has the class .cls1? */
$(ele).is(":first-child"); /* is ele first child of its parent? */
$(ele).is(":contains('Peter')"); /* does ele have a text "Peter"? */
$(ele).is(":visible");
$(ele).is(":hidden"); /* is ele hidden? */
$(ele).is(function(){/* Check some condition & return true or false */}); /* does
ele satisfy some condition? */

How to find the element which contains given string?


var foundin = $('*:contains("I am a simple string")');

***********************************************************************************
*****************************************
find function will look for given element in children of given set:
To find siblings that start with class abc, following will not work (Use filter
instead):
$(".div3").siblings().find("[class^='abc']");
Following will work:
$(".div3").parent().find("[class^='abc']");

***********************************************************************************
*****************************************
How to filter out an element within a collection or array?
$('li').filter('.test');

***********************************************************************************
*****************************************
.closest() locates target element and searches for given selector within its
ancestors and returns first matching element.
<ul class="level-2">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>

$(".item-3").closest(".level-2") returns ul.level-2.

***********************************************************************************
*****************************************
When collecting elements, a context can be passed as second parameter to the jQuery
function.

EX:
<p class="hello">Hello World</p>
<div id="wrap">
<p class="hello">Hello World</p>
</div>

var hi1 = $('.hello'), // Length is 2.


hi2 = $('.hello', $('#wrap').get(0)); // Length is 1. Equivalent to $('#wrap
.hello').

How to take parent for an element?


$("#id1").parent().css('background-color', 'blue');

$("#id1").css('cursor', 'pointer');
$("#id1").css('cursor', 'auto');

***********************************************************************************
*****************************************
<div class="div1">
<div class="div3">
<div class="div2">
<div class="div2">
</div>
</div>
</div>
<div class="div4">
</div>
<div class="div4">
</div>
</div>

How to select immediate child of an element? Use > symbol: $('.div1 > .div2')
selects nothing.
How to select descendants of an element? Use space: $('.div1 .div2') selects 2
elements.
How to select immediate sibling? Use + symbol: $(".div3 + .div4"); selects 1
element (div4 that is preceeded by div3 immediately).
How to select one of the siblings? Use ~ symbol: $(".div3 ~ .div4"); selects 1
element (div4 & div3 are siblings).

How to select an element that has 2 class? <div class="cl1 cl2"/> $


(".cl1.cl2").html("Test");

***********************************************************************************
*****************************************
What does this select?
$('.cls1','.cls2','.cls3'); //Equivalent to $('.cls3 .cls2 .cls1').
Select cls1 whose ancestor is cls2 and cls2's ancestor should be cls3.

***********************************************************************************
*****************************************
How to refer elements within an iframe?
$("#iFrame").contents().find("#someDiv").removeClass("hidden");

Refer:
http://stackoverflow.com/questions/364952/jquery-javascript-accessing-contents-of-
an-iframe

***********************************************************************************
*****************************************
To convert xml into json, use jQuery plug-in.
Take & use this js: http://jquery-xml2json-
plugin.googlecode.com/svn/trunk/jquery.xml2json.js
lovehate project uses this js.

var jsonResult = $.xml2json(xmlResult);

***********************************************************************************
*****************************************
How to display html strings?
$('#foo').text('<a href="example.html">Link</a><b>hello</b>'); // Displays html
string by escaping html operators
EX:
&lt;a href="example.html"&gt;Link&lt;/a&gt;&lt;b&gt;hello&lt;/b&gt;

$('#foo').html('<a href="example.html">Link</a><b>hello</b>'); // Displays link for


the word hello

jQuery.html() treats the string as HTML.


jQuery.text() treats the content as text.

***********************************************************************************
*****************************************
How to know whether jquery is defined already?

if(typeof jQuery == 'undefined')


{
alert('jQuery has not been loaded!');
}

if(jQuery)
{
alert('jQuery is loaded!');
}

***********************************************************************************
*****************************************
$('#id1').addClass('cls1'); addClass() just adds given class. It doesn't replace or
remove existing classes.
$('#id1').removeClass('cls1');

replaceWith:

***********************************************************************************
*****************************************
$('#id_plMask').css('background-image', 'url("' + VERSION_DIR + 'img/1.png")');
$('.rtFooterTable').css('background', 'url("' + VERSION_DIR + 'img/footer_bg.jpg")
no-repeat left bottom');

***********************************************************************************
*****************************************
How to show or hide td of a table?

Note:
Setting display: block for a td wouldn't display it correctly. td's display should
have 'table-cell'.
Use jQuery's show() & hide() methods.

***********************************************************************************
*****************************************
How to know whether an elment is empty (has no children) ?
$('.zoomCls').children().size() == 0
$('#element').is(':empty')

size() vs length:
size() returns length. Using length (faster) avoids one extra method call.

***********************************************************************************
*****************************************
$.each(
$(".cls"),
function(i, element)
{
console.log("I will be called once for each cls element");
}
);

***********************************************************************************
*****************************************
How to iterate the children of en element?

var str = '';

$(document.body).children().each(
function(idx, itm)
{
str += "id = " + $(itm).get(0).id + ", width = " + $
(itm).get(0).offsetWidth + "\n";
}
);

str += "body width = " + $(document.body).get(0).offsetWidth + "\n";

***********************************************************************************
*****************************************
How to find width or height of an element?

alert($('#id1').width());
alert($('#id1').height());

width() ==> returns integer value. EX: 100.


.css('width') ==> returns string. EX: "100px".
***********************************************************************************
*****************************************
Difference $(this) and "this"?
this refers dom element.
$(this) refers jQuery object.

How to pass dom element in click handler?


$('#id1').click(
function(evnt){this.id; /*this refers dom*/}
);

***********************************************************************************
*****************************************
How to trigger or initiale click action?
$("#id").trigger('click');

***********************************************************************************
*****************************************
Events:
$('#id1').click(function(evnt){});
$('#id1').bind('click', function(){});
$('#id1').unbind('click'); // removes all click handlers.
$('#id1').unbind(); // removes all handlers.
$('#id1').unbind('click', handler); // removes specific handler.

Unbind may not remove click handler. User prop() & attr() functions:
$('#id1').unbind('click').prop("onclick", null).attr("onclick", null);

Handler that will be called only once:


$("#foo").one("click", function(){});

$("#foo").bind(
'click',
function()
{
$(this).unbind('click', arguments.callee); //unbind *just this handler*
}
);

Event namespacing:
$('#id1').bind('click.nameSpace1', function(){});
$('#id1').bind('click.nameSpace2', function(){});
$('#id1').unbind('click.nameSpace1'); // removes first event handler. Second
handler will still receive click actions.

live():
Event handlers can be added even before elements exist.
It attaches the event handler to the root level document along with the associated
selector.
$( "#members li a" ).live( "click", function( e ) {} );

delegate():
Behaves in a similar fashion to the .live() method.
Instead of attaching the selector/event information to the document, it is added to
an element which is ancestor of element for which event is registered.
$("#members").delegate("li a", "click", function( e ) {} );
Here "members" element is ancestor of "li a". So it gets events of "li a".

undelegate():
Remove all event handlers added with the delegate() method from all elements:
$("#members").undelegate("li a", "click");

on():
.bind(), .live(), and .delegate() methods use on() method.

off():
It is similar to unbind().
It removes event handlers that were attached with .on().

***********************************************************************************
*****************************************
How to detect 'enter' key in 'input' tag?

$("#searchBox").keyup(
function(evt)
{
if(evt.keyCode == 13)
{
alert("pressed enter key");
}
}
);

***********************************************************************************
*****************************************
$("#id1").mouseover(
function(){alert("mouse over");}
);

Use mouseenter & mouseleave instead of mouseover & mouseout:


$("#id1").mouseenter(function () {
$("#id2").show();
});

$("#id1").mouseleave(function () {
$("#id2").hide();
});

***********************************************************************************
*****************************************
scrollTop is the number of pixels that the content of an element is scrolled
upward. This is same as domEle.scrollTop.
$('#containerScrollDiv').scrollTop(scrollValue.top);

***********************************************************************************
*****************************************
How to get scrollHeight in jQuery?
$('#test').prop('scrollHeight');
$('#test').get(0).scrollHeight;

***********************************************************************************
*****************************************
position() returns current position relative to the offset parent. DOM equivalent
of offsetTop & offsetLeft.
offset() returns current position relative to the document.

EX:
<tr>
<td>
<div id="1" style="width: 500px;">
</td>
<td>
<div id="2" style="width: 100px;">
</td>
</tr>

$('#2').offset().left ==> 500


$('#2').position().left ==> 0

***********************************************************************************
*****************************************
How to remove attribute of an element?
$('#id1').removeAttr('style');

***********************************************************************************
*****************************************
How to find whether an element exists?
if ($("#id1").length > 0)
{
alert("id1 exists");
}

***********************************************************************************
*****************************************
Following 2 statements are one and the same:
$(document).ready(function() {
});

Shorthand for document ready:


$(function(){
});

***********************************************************************************
*****************************************
accordion plug-in:
http://jquery.bassistance.de/accordion/demo/

***********************************************************************************
*****************************************
fadeIn would work only if
$('#' + elementId).css('display', 'none');
$('#' + elementId).fadeIn('slow',finalCbk);

***********************************************************************************
*****************************************
How to toggle display of an element?
How to show an elment if it is hidden or hide it if it is shown?
$("#id1).toggle();

$("#id1).toggleClass("abc"); // Adds class "abc" if it is not already there;


Removes it if it is already there.

***********************************************************************************
*****************************************

You might also like