Relax Breath of Solution.Community tech blog of Sameera Thilakasiri - Consultant UI, UX, RWD Specialist/ Interactive Designer

Just I wanted.. Do you?…

jQuery Tips and Tricks you Must Memorize

Posted on July 17, 2011 | Comments Off on jQuery Tips and Tricks you Must Memorize

Creating an HTML Element and keeping a reference

var newDiv = $("<div />");   //  $("<div />")  =  $("<div></div>") 
newDiv.attr("id", "myNewDiv").appendTo("body");

Checking if an element exists

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

If you want to know the index of an element within a set (e.g. list items) within a unordered list:

$("ul > li").click(function () {
    var index = $(this).prevAll().length;
});

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: "..." });

Add/remove a class based on a Boolean

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

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

$('.class:first')

Disable right-click contextual menu.

$(document).bind("contextmenu",function(e){  
         return false;  
});

Links with the rel=”external” attribute will only open in a new window

$('a[@rel$='external']').click(function(){  
       this.target = "_blank";  
}); 

Detect browser

// Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ){
	// do something
}

// Target Safari
if( $.browser.safari ){
	// do something
}

// Target Chrome
if( $.browser.chrome){
	// do something
}

// Target Camino
if( $.browser.camino){
	// do something
}

// Target Opera
if( $.browser.opera){
	// do something
}

// Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ){
	// do something
}

// Target anything above IE6
if ($.browser.msie && $.browser.version > 6){
	// do something
}

jQuery timer callback functions

window.setTimeout(function() {  
      // do something  
}, 1000); 

Count a element

$("p").size();

No conflict-mode
To avoid conflict other libraries on your website, you can use this jQuery Method, and assign a different variable name instead of the dollar sign.

var $jq = jQuery.noConflict();  
$jq('#id').show();  

Author
Sameera Thilakasiri By Sameera Thilakasiri
,is a front-end developer based in Colombo, is a blogger and a lifestyle photographer.
Follow him Twitter and Google+. Check out him.

Comments

Comments are closed.