Saturday, 23 January 2016

Jquery events(click,bind,live,delegate,on)

(1)click
=======================================================
$(document).ready(function(){
$("li").click(function(){
$(this).css("color","red");
});
});

(2)bind
=========================================================
$(document).ready(function(){
$("li").bind("click",function(){
$(this).css("color","red");
});

$("li").bind("click mouseover moveout",function(event){
if(event.type=="click")
$(this).css("color","red");
});

});

(3)live
=============================================================

$(document).ready(function(){
$("li").live("click",function(){
$(this).css("color","red");
});
});

live function is introduced in 1.1 jquery it was completely removed in 1.9.

(4)delegate
============================================================

We can perform event delegation using delegate.means we have to attach event to parent it will bubble the event to children.

$(document).ready(function(){
$("li").delegate("click",function(){
$(this).css("color","red");
});

$("ul").delegete("li","click",function(event){
if(event.type=="click")
$(this).css("color","red");
});

});

(5)on
===========================================================

$(document).ready(function(){
$("li").on("click",function(){
$(this).css("color","red");
});

$("li").on("click mouseover moveout",function(event){
if(event.type=="click")
$(this).css("color","red");
});

});

if we want to append dynamically added controls click event.the best way to do is identify the parent control and bubble that event to child control

Ex:

$(document).ready(function(){
$("ul").on("click","li",function(){
$(this).css("color","red");
});
});

if we want to send an data in event

$(document).ready(function(){
$("li").on("click","{'name':'das','email':'mariyadasu67@gmail.com'}",myfunction
});

function myfunction(event)
{
console.write(event.data.name+" "+ event.data.email);
}


all event jquery recommended to use on event.

No comments:

Post a Comment