Handling Events using JavaScript
Question: What type of JavaScript code do you write to handle a button click event?
Answer It depends on the browser!
Event Attachment Techniques Most Browsers
mybutton.addEventListerer(‘click’,function() {}, false);
Internet Explorer
mybutton.attachment(‘onclick’,function() { });
If you want to enrich your career and become a professional in JavaScript, then visit Tekslate - a global online training platform: "JavaScript Training" This course will help you to achieve excellence in this domain.
jQuery Event Model Benefits
Events notify a program that a user performed some type of action jQuery provides a cross-browser event model that works in IE, Chrome, Opera, Firefox, Safari and more jQuery event model is simple to use and provides a compact syntax
<html><head>
<script type=”text/javascript” src=”jQuery.js”>
</script>
</head>
<body>
<button id=”buttonId”>
click</button>
<script type=”text/javascript”>
var myButton=document.getElementById(“buttonId”);
if(document.addEventListener)
{
myButton.addEventListener(“click”,function())
{
alert(“click Button”);
},
false);
}
else{
mybutton.attachEvent(“onclick”,function(){alert(“click IE Button”);
}); }
</script>
</body>
</html>
Handling Click Events
Raising a click event from within another function:
$(‘#otherID’).click(function()
{ $(‘#myID’).click(); });
This would fire when the element otherID was clicked and raise the click event for myID
<html><head>
<script type=”text/javascript” src=”jQuery.js”>
</script>
$(document).ready(function()
{ $(‘#buttonid1’).click(function()
{ // raising the event using jQuery function
alert(“button1 is clicked”); $(“#buttonld2”).click(); });
$(“#buttonid2”).click(function()
{
alert(“button2 is clicked”);
});
});
</script>
</head>
<body>
<button id=”buttonid1”> click</button>
<button id=”buttonid2”> click2</button>
</body>
</html>
<html>
<head>
<script type=”text/javascript” src=”jQuery.js”></script> <script type=”text/javascript”>
$(document).ready(function()
{
alert(“City Dropdown changed to :” + $(this).val());
});
});
</script>
</head>
<body>
<select id=”cityId”>
<option value=”hyd”>Hyderabad</option>
<option value=”hyd”>Hyderabad</option>
<option value=”bang”>Banglore</option>
<option value=”mumbai”>Mumbai</option>
<option value=”hyd”>Hyderabad</option>
</select>
</body>
</html>
Handling Click Events
click(handler(eventObject)) is used to listen for a click event or trigger a click event on an element
$(‘#myID’).click(function(){ alert(‘The element myID was clicked’); });
<html>
<head>
<script type=”text/css”>
.Hilight:
bigground-color:pink;
}
</style>
<script type=”text/javascript” src=”jQuery.js”>
</script>
<script type=”text/javacript”>
$(document).ready(function()
{
$(“div#myDiv”).click(function(event)
{ $(this).addClass(“Hilight”); var result=””;
result=result+”x:”+event.pageX+”<br/>”;
result=result+”Y:”+event.pageY+”<br/>”;
result=result+”keycode:”+event.keycode+”<br/>”;
result=result+”TimeStamp:” + event.timeStamp+”<br/>”;
result=result+”Target element ID:”+$(event.target).attr(“id”)+”<br/>”;
result=result+”Event type:” + event.type+”<br/>”; $(this).html(result); });
});
</sript>
</head>
<body>
<div id=”myDiv” style=”width:400px;height:200px;border:2px solid black;”>
This is my div This is my div This is my div This is my div
</div>
</body>
</html>
<html>
<head>
<script type=”text/css”>
.Hilight: bigground-color:pink;
}
</style>
<script type=”text/javascript” src=”jQuery.js”>
</script>
<script type=”text/javacript”>
$(document).ready(function()
{
$(“div#myDiv”).mouseenter(function()
{
$(this).toggleclass(“Hilight”); }).mouseleave(function()
{ $(this).toggleclass(“Hilight”); }
}
.click(function(event){ $(this).text(“X: “+event.pageX+”Y:”+event.pageY);
}};
}};
</sript>
</head>
<body>
<div id=”myDiv” style=”width:400px;height:200px;border:2px solid black;”>
This is my div This is my div This is my div This is my div This is my div
</div>
</body>
</html>
Using bind()
.bind(eventType,handler(eventObject))
attaches a handler to an event for the selected element(s)
$(‘#MyDiv’).bind(‘click’,function())
{
//Handle click event });
.click() is the same as .bind(‘click’)
Using unbind()
unbind(event) is used to remove a handler previously bound to an element:
$(‘#test’).click(handler); can be unbound using
$(‘#text’).unbind(); Specific events can also be targeted using unbind():
$(‘#test’).unbind(‘click’);
Binding Multiple Events using jQuery
bind() allows multiple events to be bound to one or more elements Event names to bind are separated with a space:
$(‘#MyDiv’).bind(‘mouseenter mouseleave’, function(){ $(this).toggleclass(‘entered’); } );
<html>
<head>
<script type=”text/css”>
.Hilight: bigground-color:pink;
}
</style>
<script type=”text/javascript” src=”jQuery.js”></script>
<script type=”text/javacript”>
$(document).ready(function()
{
$(“div#myDiv”).bind(“mouseenter mouseleave click”,function(event)
{ $(this).toggleClass(“Hilight”); if(envetscope==’click’)
{ $(this).add(“X:” + even.pageX+”Y:”+event.pageY); } });
$(“button”).click function(){ //$(“divmyDiv”).unbind();
$(“div#.Div”).unbind(“click”); }}; });
</sript>
</head>
<body>
<div id=”myDiv” style=”width:400px;height:200px;border:2px solid black;”>
This is my div This is my div This is my div This is my div This is my div
</div>
<button>Unbind even button</button>
</body>
</html>
live() and delegate() Functions
- live() and delegate() allow new elements added into the DOM automatically be “attached” to an event handler
live() – Allow binding of event handlers to elements that match selector, including future elements. Events bubble upto the document object.
delegate() – Replacement for live() in jQuery 1.4 Attaches an event handler directly to the selector context.
Using live()
- Event handlers can be set using live()
- The document object handles events by default
- Works even when new objects are added into the DOM:
$(‘.someclass’).live(‘click’,someFunction); Stop live event handling using die(); $(‘.someClass’).die(‘click’,someFunction);
Click Event
<spanclass=”someclass”/>
<p class=”someclass”/>
<div class=”someClass”/>
Using delegate()
Newer version of live() added in jQuery 1.4 A context object (#Divs in the sample belpw) handles events by default rather than the document object Works even when new objects are added into the DOM: $(‘#Divs’).delegate(‘div’,’click’,someFunction); Stop delegate event handling using undelegate()
How delegate() works
Click Event
<span class=”someclass”/><p class=”someClass”/>
<div class=”someclass”/>
<html>
<head>
<script type=”text/javascript”src=”jQuery.js”></script>
<script type=”text/javascript”>
$(document).ready(function()
{ var PhoneDiv=$(“div#newDiv”);
$(“#AddPhoneButton”,click(function(){ var phoneType.Clone=$(“div:eq(0)”.PhoneDiv).clone();
var PhoneNumber.Divclone=$(“div:eq(1)”,PhoneDiv).clone();
$(“select”,phone.typeDivclone).val(“);
$(“input”,phone.NumberDivclone).val(‘’)l PhoneDiv.apper(“<div style=’clear:both’/>”
.append(PhoneTypeDivcloappend(PhoneNumberDivclone)));
$(“input”,PhoneDiv).keypress”,function(event){
if(event.keycode(48) || event.keycode>57)
{
//even propagation();
return;
} }};
$(“button”).click(function)
{
// $(“input”,phoneDiv).die(); $(“input”,Phonediv).die(“keypress”);
});
PhoneDiv.delegate(“im”,”keypress”,function(event){ if(event.keycode 48 || event.keycode>57)
{
//even popPropagatation();
return;
} }
0;
$(“button”).click(function)
{ PhoneDiv.undelegate(“input”,”keypress”);
}}; }};
</script>
</head>
<body>
<table boarder=”1”>
<tr>
<td>Name</td>
<td> <input type=”text”,name=”name”/> </td>
</tr>
<tr>
<td> Password </td>
<td> <input type=”password” name=”password” /> </td>
</tr>
<tr>
<td> Address</td>
<td> <textarea cols=”50” rows=”4”></textarea> </td>
</tr>
<tr>
<td>Phone</td>
<td> <input type=”submit” id=”AddPhoneButton” value=”AddPhone”/>
<div id=”PhoneDiv”> <div id=”PhoneTypeDiv” style=”float:left”>
<select name=”PhoneType”>
<option value=””>Select One</option>
<option value=”Mobile”>Mobile</option>
<option value=”Office”>Office</option>
<option value=”Home”>Home</option>
</select>
</div>
<div id=”PhoneNumberDiv” style=”float:left”>
<input type=”text” name=”PhoneNumber”/>
</div>
</div>
</td>
</tr>
<tr>
<td>City</td>
<td> <select id=”cityID”>
<option value=”hyd”>Hyderabad</option>
<option value=”bang”>Banglore</option>
<option value=”chennai”>chennai</option>
<option value=”mumbai”>Mumbai</option>
</select>
</td>
</tr>
<tr>
<td colspan=”2” align=”center”> <input type=”submit” value=”submit”/> </td>
</tr>
</table>
<button>Release Event Handlers</button>
</body>
</html>