Enhancing Raphael elements with event handling functionality

Greetings! I've been attempting to implement a mousemove and click event on an SVG Raphael Rectangle:

Check it out here: http://jsfiddle.net/neuroflux/nXKbW/1/

Here's the code snippet:

tile = ctx.rect(x*10,y*(i*10),10,10).attr({
    fill:'#000000',
    stroke: '#ffffff'
});
tile.mouseover(function(e) {
    pX = e.pageX;
    pY = e.pageY;
});
tile.click(function() {
    console.log('x: '+pX+'| y:'+pY);
});

Unfortunately, despite my efforts, it seems like this isn't working properly - no output is displayed onClick :'(

Answer №1

Finally got the click function to work! Woohoo 🎉.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <script type="text/javascript" src="https://github.com/DmitryBaranovskiy/raphael/raw/master/raphael-min.js"></script>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
        <script type="text/javascript">
            /* GLOBAL VARIABLES */
            var drawFrames;
            var canvas;
            var ctx;
            var universe = new Array();
            var tile;
            var pX,pY = 0;

            universe = (
                [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
                [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
                [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
                [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
                [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
                [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
                [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
                [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
                [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]],
                [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]]
            );

            /* WINDOW LOAD */
            window.onload = function() {
                init();
            }

            /* INITIALISATION */
            function init() {
                ctx = Raphael(10, 50, 320, 200);
                drawFrames = setInterval(drawFrame, 40);
            }

            /* FRAME RENDER LOOP */
            function drawFrame() {
                //ctx.clear();
                for (var x = 0; x < universe.length; x++) {
                    for (var y = 0; y < universe[x].length; y++) {
                        for (var i= 0; i < 11; i++) {
                            tile = ctx.rect(x*10,y*(i*10),10,10).attr({
                                fill:'#000000',
                                stroke: '#ffffff'
                            }).click(function(e) {
                        console.log('x: '+e.pageX+'| y:'+e.pageY);
                        })
                    }
                }

            }
        }
        </script>
    </head>
    <body>
        <canvas id="main" width="800" height="600">
            <h1>No Support I'm Afraid...</h1>
        </canvas>
    </body>
</html>

Answer №2

Start by assigning an id to your raphael object and then attach the click event to it.

tile = ctx.rect(x*10,y*(i*10),10,10).attr({
fill:'#000000',
stroke: '#ffffff'
});
tile.node.id='unique_tile_id';
$('#unique_tile_id').bind('click',function(){alert('clicked');});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am looking to implement a Mouseover effect on my Canvas element using JavaScript

To create a mouseover effect only on a specific canvas location, I have developed the MousePosition function (as seen below). The commands for the mouseover effect should be implemented within the MouseOverButton function. However, despite my efforts, it ...

Alert: Unauthorized hook call and Exception: Cannot access properties of null (reading 'useState')

I am currently working on a project using ASP.NET Core with React. To bundle my code, I have opted to use Webpack 5. Within the index.jsx file, I have the following code: import { useState } from "react"; function App() { const [value, setV ...

Employing the power of JavaScript to enable the seamless toggle of an overlay

I have a div named "navbar_menu". On clicking this div, I want the visibility of the div named "nav_overlay" to fade in. Upon another click, I want it to fade back and become invisible again. Currently, I have set the div 'nav_overlay" to have ' ...

Challenge with Expect.js validation in a lesson on Codeacademy

I am currently developing a lesson on Codecademy to teach users about the construction of HTML forms. This project is mainly for my own enjoyment, just to keep everyone in the loop. After reviewing the submission test guidelines and API, I made the decisio ...

Tips for integrating Material UI Drawer with Redux

I have been attempting to incorporate a Drawer feature that displays on the left side while utilizing Redux to maintain the state of the Drawer. Unfortunately, I seem to have made an error as my onClick events are not responsive. Here is the code: Reduce ...

Reorganize divisions using Bootstrap

I am exploring different ways to manage responsiveness through the reordering of divs. While I am aiming for a solution that is highly flexible, any suggestion would be appreciated. Desktop View: https://i.stack.imgur.com/boSOa.png Mobile View: https:// ...

Tips for linking together AJAX requests with vanilla JavaScript

I have searched extensively for solutions using only plain JavaScript, but I have not been able to find a suitable answer. How can I tackle this issue with pure JavaScript given that my repetitive attempts haven't yielded any results? function ...

Guide to creating a Javascript API wrapper

I'm currently working on a React client and I have a question regarding the implementation of a JavaScript wrapper. The APIs I am using return more data than is necessary for the client, so I want to create an index.js file where I can call the API, r ...

Customize the number of slides in Glide.js after navigating using the controls

I have incorporated a glide JS carousel to display content in a carousel format. The documentation for this repository can be found on their official website as well as on Github. Here is my current code snippet: jQuery( window ).load(function() { va ...

Encountered an error when attempting to extend the array function: Uncaught TypeError - Object [object Array] does not contain a 'max' method

Hello, I am currently attempting to integrate this function into my code: Array.getMaximum = function (array) { return Math.max.apply(Math, array); }; Array.getMinimum = function (array) { return Math.min.apply(Math, array); }; This is inspired ...

What steps should be followed to upgrade node.js from version 5.9.1 to 6.14.0 in a secure manner

Our current node version is 5.9.1 and we are looking to transition to a newer version that supports ES6. Specifically, I am aiming to upgrade to at least version 6.14.0, which is known to support almost all of the ES6 features. However, I must admit that ...

Axios delivers the index.html data to the front end of a React.js application

I’m currently in the process of developing a web application using React.js for the front-end and Flask for the back-end. I attempted to establish a connection between the two by defining a proxy server in React and enabling CORS in Flask. Everything was ...

Retrieving user and groups information using Express.js and Node.js with OKTA

Is anyone else experiencing an issue with retrieving user info and group info using the OKTA API? The responses are being sent as strings, requiring me to use JSON.parse() before I can work with the data. Has anyone found a solution to this problem? ...

The screen is cloaked in a dark veil, rendering it completely inaccessible with no clickable

Utilizing Bootstraps modals, here is my current layout. Within the site's header, there exists a "settings" button that triggers a modal containing various options. These options are not tied to the question at hand. The button responsible for displ ...

Guide to extracting the value of an attribute from a Meteor collection object

In my database, I have a collection called Meteor.users. Each user in this collection has an attribute named “lastQuestionAnswered”, which stores the questionId of the last question they answered. { "_id" : "jrCJiuo7eprNFKfLG", "name" : "Elon Musk", " ...

Three.js: Modifying values within dat.GUI is not allowed

I have added a "comboBox" to my dat.GUI instance in order to select possible values. However, when I run my application, the dat.GUI appears with the comboBox but it seems to be frozen - I cannot change its default value. Below is the code snippet that dem ...

Difficulty in displaying accurate visuals for Albers US Choropleth Map using d3.js and React

I'm currently troubleshooting my code as I'm only seeing a large square of one color when I attempt to create a colorScale for each element with the class "county" on this Albers US map. The desired outcome is something similar to this project: ...

Organize the dataset into groups based on every possible key

Hi there, I'm facing a challenge while developing an application using NestJS/Prisma. The task at hand is to extract unique results from a table in order to display them in a filter on the front-end. Let me give you an overview of my table structure ...

Pause for a brief moment before proceeding to the next task within the map

My situation involves having a list of usernames that represent accounts: let users = [ "user1","user2","user3","user4","user5","user6","user7" ] users.map(async (user, i) => { co ...

HighCharts: visualize vertical stacked bars displaying the distribution of percentages within each stack

I currently have a stacked bar chart similar to the one shown in this JSFiddle demo. My goal is to transform the stacks so that each bar represents a percentage of the total stack height. For instance, in the Apples stack we currently have values {3, 2, 5 ...