views:

477

answers:

1

Hi,

I am new to RaphaelJS. I am trying to add click listener and keyboard listener to the canvas with no success. Can someone please explain how to use click listener and keyboard listener on Raphael. A small example will be of great help.

Thank you.

+1  A: 

Here is a click and mouseover example, you can use more jQuery in there to simplify it but I just wanted to use the document ready function. Shouldn't be too much to add a keyboard event in there:

<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://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
        <script type="text/javascript">
            $(document).ready(function()
            {
                var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);  
                var circ = paper.circle(250, 250, 40);  
                circ.node.onmouseover = function()
                {  
                    this.style.cursor = 'pointer';  
                };

                circ.node.onclick = function() 
                {    
                    circ.animate({opacity: 0}, 2000, function()
                    {                
                        this.remove();  
                    });
                } 
            });
        </script>
        <style type="text/css"> 
            #canvas_container
            {  
                width: 500px;  
                border: 1px solid #aaa;  
            }  
        </style>
    </head>
    <body>                                                       
        <div id="canvas_container"></div>
   </body>
</html>
Ambrosia
Nice - however the events are only triggered on the border of the circle. (as it is no filled circle)
Ghommey
Easily modified with: circ.attr('fill', 'red');
Ambrosia
Hey thanks a lot, it works fine. Is there a way to include this to a widget that is created using the raphaeljs components?
sprasad12
I'm sorry I'm not sure what you mean. If you have a drawing created by RaphaelJS, you just use the event handler function assignment on the element... you could use jQuery to help you if you have lots of the same kind of element. Like for all your <div class="canvas"></div> you use $('.canvas').click(function(){}); kind of statements in your $(document).ready(function(){}); statement
Ambrosia