0

I'm a begginer with Javascript and I would like to know if there is a better way to write this piece of code:

var images = [], 
index = 0;
images[0] = "<a href = 'link' onclick='_gaq.push(['_link', this.href]);return false;'>
<img src='image.jpg'></a>";
images[1] = "<a href = 'link1' onclick='_gaq.push(['_link', this.href]);return false;'>
<img src='image1.jpg'></a>";
index = Math.floor(Math.random() * images.length);
document.write(images[index]);

This code doens´t work, I think is because I'm including the onClick function inside the variable description...

The function would be to print randomically the images, but adding the _gaq.push parameters in the url image link.

Is there any other way the write this code?

Thanks

1
  • You can add event handlers without using inline versions. You can select the images in code and assign the onclick properties or add handlers for the click events to allow other handlers to be attached as well if you wish. Commented Mar 15, 2013 at 20:07

1 Answer 1

1

No need to create the html in javascript. You can do the following:

JavaScript (must be instantiated before the html is rendered):

var pushMe = function(link){
    _gaq.push(['_link', link.href]);return false;
};

Html:

<a href = "link" onclick="pushMe(this);">
<img src="image.jpg"></a>
Sign up to request clarification or add additional context in comments.

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.