0

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";
});
1
  • i doubt arrays have a .click function... Commented Jul 24, 2012 at 17:31

4 Answers 4

1

The jQuery $.each function can help you with this;

$.each(myArray, function(i, v) {
    v.click(function() {
        window.location = "http://somewebsite.com";
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

1

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
               });

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.