Adding and Removing Event Listeners

Problem

I want to add an event listener to or remove an event listener from a DOM object. (In other words, I have a thing I want to be able to click on and have it do something.)

Solution

FBJS supports the standard addEventListener() and removeEventListener() methods that you know and love from traditional JavaScript. Calling them is as simple as finding your target in the DOM and passing in your event type and function name:

var myObj = document.getElementById('someId');
myObj.addEventListener('click', otherFunctionName);
myObj.removeEventListener('click', otherFunctionName);

Discussion

This is pretty simple, as long as you keep in mind that otherFunctionName needs to be a defined JavaScript function, and that your new listeners will join any that were added in the FBML code (e.g., <div id="someId" onclick="aFunctionName();">).

Get Facebook Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.