O'Reilly logo

Facebook Cookbook by Jay Goldman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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();">).

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required