views:

297

answers:

3

Hi guys,

I have attached a event to a text box using addEventListener. It works fine. My problem arouse when i wanted to trigger the event programmatically from another function.

how can i do it?

A: 

You can use jquery to trigger a event programmatically. for more details see http://api.jquery.com/trigger/

Anantha Kumaran
+3  A: 

You can use fireEvent on IE, and w3c's dispatchEvent on most other browsers. To create the event you want to fire, you can use either createEvent or createEventObject depending on the browser.

Here is a self-explanatory piece of code (from prototype) that fires an event dataavailable on an element:

  var event;
  if (document.createEvent) {
    event = document.createEvent("HTMLEvents");
    event.initEvent("dataavailable", true, true);
  } else {
    event = document.createEventObject();
    event.eventType = "ondataavailable";
  }

  event.eventName = eventName;
  event.memo = memo || { };

  if (document.createEvent) {
    element.dispatchEvent(event);
  } else {
    element.fireEvent(event.eventType, event);
  }
Alsciende
A: 

I am using the following functions to do my task. It works fine when cursor moves away from textbox but if i want to fire the same event from code say like next function i get error...

function addEvent( obj, type, fn ) {
    if (obj.addEventListener) {
        obj.addEventListener( type, fn, false );
    }
    else if (obj.attachEvent) {
        obj["e"+type+fn] = fn;
        obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
        obj.attachEvent( "on"+type, obj[type+fn] );
    }
    else {
        obj["on"+type] = obj["e"+type+fn];
    }
}

function addEventByName(ObjName, event, func){
    MyEle = document.getElementsByName(ObjName);
    addEvent(MyEle[0], event, func);
}

addEventByName("txtBox", 'blur', function(){
    alert('hello');
});

function fire(){
    x = document.getElementsByName('txtBox')[0];
    x.blur(); //gives error
    x.onblur(); //gives error
}
KoolKabin