Javascript pass parameters to onclick function in loop

Any ideas to make this script work?

I have two paragraphs:

<p data-color="red">This textarea has a character limit of 50.</p>
<p data-color="blue">This one has a character limit of 40.</p>​

And some JS:

<script>
var p = document.getElementsByTagName('p'),
    i = p.length;

while (i--) {
    color = p[i].getAttribute('data-color');
    p[i].onclick = function() {
        this.style.color = color;
    };
}​
</script>​

Demo

I want the paragraphs to turn their specified colors when clicked. I need to pass each element's color into the onclick function.

Any Ideas?

Thanks so much in advance!

Answers


<script>
var p = document.getElementsByTagName('p'),
    i = p.length;

while (i--) {
    p[i].onclick = function() {
        this.style.color = this.getAttribute('data-color');
    };
}​
</script>​

OK, being downvoted bothers me, so I gave this another shot. Pure JS. Here's what I came up with. There's really no way, as was pointed out, to pass the color into the function as a variable. So instead, attaching a class to the paragraph tag and using that class as the color seemed the only way to avoid jQuery and offer a very simple solution. Since none of the paragraphs in the example code had classes to begin with, this seemed a viable solution. Here's my jsFiddle.


Need Your Help

Add slash to an enumeration in Java

java enums enumeration slash

I need to create an enumeration like this:

how to move logo to top in html

html css

Hi in the below website http://olisvell.com/responsivedesign/index.html logo i want to move to top.