Tagged with: JavaScript
Calling jQuery Functions From Flash
Recently I took on a freelance project building a Flash module for a company. There were other components to the site built in html/css by their in-house front-end team, and the team had hooked up a form to display using jQuery. They wanted a button in the Flash module trigger the form’s visibility.
At first, I thought, “no problem, jQuery is JavaScript, right? Calling JavaScript functions from Flash should be a no brainer – just use Flash’s ExternalInterface!” But for some reason, i wasn’t able to access the jQuery method. The button in Flash was clickable, but nothing happened. I wasn’t getting any JavaScript or ActionScript errors, either.
Stumped, I sat there for a few hours, debugging and trying to figure out if it was something not done right in Flash. I looked on Google as well, and couldn’t find any articles on how to call jQuery methods from Flash.
Finally, I came upon some random forum post (which I’ve now lost) where a person had asked if it was possible to trigger a button event. A lightbulb went off in my head – the jQuery method was able to be called from a button click in the html page using the jQuery $(‘#htmlElement’).click(); mouse event, would I be able to fake (or trigger) a button click event?
YES! I wrote a quick JavaScript function outside of the jQuery $(document).ready(); method whose sole purpose was to trigger the button click event, and had flash call that JavaScript Function. Code below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function jsFunction() {
jQuery('.formLink').trigger('click');
};
$(document).ready(function() {
function displayForm() {
//code that displays and hides the form goes here
}
$('.formLink').click(function(){
displayForm();
});
});
</script>
</head>
<body>
<!-- sample HTML Button Link -->
<a class="formLink" href="javascript:void(0);">Ask Us</a>
</body>
</html>
*This example points to a local copy of jQuery. Download your own copy from the Downloading jQuery page. Also, it’s good practice to place custom scripts in their own files and reference them using the script element’s src attribute, but for the sake of the example, I simply left it within the HTML.
and in Flash:
import flash.external.ExternalInterface;
ExternalInterface.call("jsFunction", "");
I decided to write a blog post on this because it took me a while to find a solution to my problem. I hope someone finds this helpful! jQuery is still relatively new to me so if you notice anything wrong with my example, or know of a better method, please feel free to comment below.

