I am using the following functions to do my task. It works fine when cursor moves away from the textbox but if I want to fire the same event from code say like next function I get an error…
JavaScript
x
29
29
1
function addEvent( obj, type, fn ) {
2
if (obj.addEventListener) {
3
obj.addEventListener( type, fn, false );
4
}
5
else if (obj.attachEvent) {
6
obj["e"+type+fn] = fn;
7
obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
8
obj.attachEvent( "on"+type, obj[type+fn] );
9
}
10
else {
11
obj["on"+type] = obj["e"+type+fn];
12
}
13
}
14
15
function addEventByName(ObjName, event, func){
16
MyEle = document.getElementsByName(ObjName);
17
addEvent(MyEle[0], event, func);
18
}
19
20
addEventByName("txtBox", 'blur', function(){
21
alert('hello');
22
});
23
24
function fire(){
25
x = document.getElementsByName('txtBox')[0];
26
x.blur(); //gives error
27
x.onblur(); //gives error
28
}
29
Advertisement
Answer
Adapting the code given as a jQuery extension in this answer, here’s a function you can use to programmatically fire an event cross-browser:
JavaScript
1
14
14
1
function fireEvent(el, eventType)
2
{
3
if (document.createEvent)
4
{
5
var evt = document.createEvent("HTMLEvents");
6
evt.initEvent(eventType, false, false);
7
el.dispatchEvent(evt);
8
}
9
else if (document.createEventObject)
10
{
11
el.fireEvent("on" + eventType);
12
}
13
}
14
Your fire
function would then look like this:
JavaScript
1
3
1
var x = document.getElementsByName("txtBox")[0];
2
fireEvent(x, "blur");
3