views:

662

answers:

2

I'm trying to find a way to trigger an event when a mouse clicks on some text generated from Raphael JS. In Firefox, the click event works perfectly, in IE 7 and 8 (I haven't tested earlier versions) neither click nor mousedown work. Click works fine for other raphael objects, e.g. the rectangle in the example.

How can I trigger an event on the text given in the demonstration below:

<html>
    <head>
        <script type="text/javascript" src="http://github.com/DmitryBaranovskiy/raphael/blob/master/raphael-min.js?raw=true"&gt;&lt;/script&gt;
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"&gt;&lt;/script&gt;
    </head>
    <body>

    <div id="graph"></div>

    <script language="javascript">
        function setupImage() {
            var canvas = Raphael(graph, 200, 200);

            var alpha = canvas.text(100, 10, "Two Words");
            alpha.attr("font-size", "20px");

            var beta = canvas.rect(50, 50, 50, 50);
            beta.attr("fill", "#3333cc");

            canvas.safari();

            var textClickEvent = function(event) {
                alert("text clicked");
            };

            var boxClickEvent = function(event) {
                alert("box clicked");
            }; 

            $(alpha.node).click(textClickEvent);
            $(beta.node).click(boxClickEvent);
        }

        $(window).load(setupImage);
    </script>

    </body>
</html>

My gut feeling is I may have to try manipulate the DOM to wrap the text in, e.g., an A element and bind on that instead. That doesn't seem like the cleanest solution so I'm asking here to see if anyone has an alternative approach.

+3  A: 

Why not just use the raphael built in event coding like this:

alpha.node.onclick = textClickEvent;
beta.node.onclick = boxClickEvent;

or you could also do this:

alpha.click(textClickEvent);
beta.click(boxClickEvent);

The rest of your code is fine.

Some helpful links: Raphael events section and Raphael node section.

ryanulit
Thanks, the alpha.click(textClickEvent) worked perfectly. I was previously trying to alpha.node.onclick = textClickEvent but that doesn't work in IE. Great, no need for jQuery! Cheers again.
Mike
A: 

A live demo of all Raphael events can be found here: http://www.irunmywebsite.com/raphael/additionalhelp.html?q=usingelementevents

Chasbeen