Reputation: 3324
I am using Raphael JS, but I think this is pure JavaScript or maybe jQuery question.
I have two elements a text and an circle(ellipse) and I am using a variable to store them for later usage.
So, I was thinking that instead of repeating myself over and over again I will create an array and use it on click.
But it is not working. How to solve this problem and assign onclick for every variable(object) in my array?
var circle = paper.ellipse(350, 320, 95, 90);
var text = paper.text(350, 320, "My text");
var myArray = [circle, text];
myArray.click(function () {
window.location = "http://somewebsite.com";
});
Upvotes: 0
Views: 142
Reputation: 481
If you want to do it with raphaelJS ...
var circle = paper.ellipse(350, 320, 95, 90);
var text = paper.text(350, 320, "My text");
var click_set = paper.set();
click_set.push(circle);
click_set.push(text);
click_set.click(function(){
// do what you want ... this function will automatically be bound to all the elements that //you push in the set
});
Upvotes: 1
Reputation: 46657
Just loop over the elements and append the handler to each of them. No need for any libraries.
var circle = paper.ellipse(350, 320, 95, 90);
var text = paper.text(350, 320, "My text");
var myArray = [circle, text];
var handler = function () {
window.location = "http://somewebsite.com";
};
for (var i = 0; i < myArray.length; i++) {
myArray[i].onclick = handler;
}
Upvotes: 0
Reputation: 59667
You needn't store the objects in an array if you just want to keep them around, you've already referenced them with two variables: circle
and text
. Define the function once and then assign it to any element that uses it:
var circle = paper.ellipse(350, 320, 95, 90);
var text = paper.text(350, 320, "My text");
function clickFunction()
{
window.location = "http://somewebsite.com";
}
circle.addEventListener("click", clickFunction);
text.addEventListener("click", clickFunction);
Or, using jQuery:
circle.click(clickFunction);
text.click(clickFunction);
Upvotes: 1
Reputation: 5689
The jQuery $.each function can help you with this;
$.each(myArray, function(i, v) {
v.click(function() {
window.location = "http://somewebsite.com";
});
});
Upvotes: 1