I have an Raphael element with click event handler:
var paper = Raphael("container", 770, 160);
var c = paper.rect(10, 10, 50, 50);
c.click(function () {
alert("triggering");
})
How I can manually fire this event? (c.click()
don't work)
Thanks!
Although this question is already answered, I will post my solution which I found out by random. It's possible with the Raphael internals:
When you attach an event listener like element.click(func)
then the element
object holds an array with all events. In this array there's an object which has a method f
(strange naming convention) which triggers the event.
So to sum it up you can call your event with knowing the order of your events, in your case there's just the click
event which is on index 0, you can call it like: c.events[0].f();
A more generic solution would be a function like
function triggerClick(element) {
for(var i = 0, len = element.events.length; i < len; i++) {
if (element.events[i].name == 'click') {
element.events[i].f();
}
}
}
But beware that if you had multiple click
events all were triggered.
Here's a fiddle to demonstrate.
Even though this has already been answered a while ago, I was looking for something a little "more native" in nature. Here's how I go about it without relying on Mootools or jQuery.
var evObj = document.createEvent('MouseEvents');
evObj.initEvent('click', true, false);
c.node.dispatchEvent(evObj);
This basically creates the event in the browser and then dispatches it to the node associated with the Raphaël object.
Here's also the MOZ link for reference: https://developer.mozilla.org/en-US/docs/DOM/document.createEvent
I actually found a slightly more elegant way to use Kris' method. Raphael supports native extension of the element object so I built a little patch to add the trigger method to raphael
here it is:
//raphael programatic event firing
Raphael.el.trigger = function (str, scope, params){ //takes the name of the event to fire and the scope to fire it with
scope = scope || this;
for(var i = 0; i < this.events.length; i++){
if(this.events[i].name === str){
this.events[i].f.call(scope, params);
}
}
};
I set up a Js fiddle to show how it works: here
EDIT :
The solution purposed by Dan Lee is working better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With