<input type="text" id="testName" onclick="EventHandlerFunction()" />
Also, it can be done in another way, inside script tag like as follows:
<script type="text/javascript" >
window.onload=function(){
document.getElementById('testName').onfocus = function(){
//do something
}
}
<script>
Remember, window.onload part is crucial. The attaching events are always need to be attached after the document object model(DOM) loaded properly. If you try to attach event outside this function, you will get an script error like stating that no such element found(this is natural as before the this element loaded, script won't found anything as this).
The above functionality can also be done in jquery easily as follows:
$(document).ready(function({
$("testName").bind('focus',fucntion({
//do something
}));
}));
the $().bind() is the most generic form for attaching event. However you can do shortcuts for several common event like
$("testName").focus(fucntion({
//do something
});)
Now consider this situation, you are making some DOM element on the fly, dynamically with your JavaScript. You want to attach event with them. You can do this in either of the following way:
//basic javascript
var dynamic_element = "<input type="button" onclick="ClickhandlerFnction()"></input>";
obj.innerHTML = dynamic_element;
//jquery
var dynamic_element = $("<input>");
dynamic_element.attr("type","button");
dynamic_element.click(ClickhandlerFnction);
now, think, if you have to make several elements(but of same type, like same tag name or same class), you will have to go thorough a loop or have to attach event to all of them manually.
Another situation, you are getting html response through ajax request and you are interested to attach event to some of those elements, either you have to do it after receiving the ajax response or have to run a continuous function with setting interval to check whether any object of the specific type has been on the document.
You can have a better solution with jquery. From jquery 1.3.x , there is a new method implemented name live that do our this kind of complex jobs simply. you can attach event to an element that not yet on the DOM, but will be available anytime in future, jquery will keep track of that and will attach that event handler as soon as it find an element of that particular type. simply write:
$(element).live('click',EventHandlerFucntion);
and you are don't be worry about whether this element is currently exist or not, or when some request is going to bring it, you just got it. You can read more about live function on jquery's live documentation.










0 comments:
Post a Comment