I have an array of elements, to which I want to apply a certain onclick event. What is the correct way of doing so (if possible at all)?
The function I want to apply to every element is this:
function fade(element){
var o = 1.0;
var x = setInterval(function(){
element.style.opacity = o;
o -= 0.01;
if(o <= 0) {
element.style.display = "none";
clearInterval(x);
}
}, 10);
}
This is what I'm trying to do:
<script type="text/javascript">
var el = document.getElementsByClassName("circle");
console.log(el[0]);
for(var i = 0; i < el.length; i++){
el[i].onclick = function(){ fade(el[i]); }
}
</script>
That is, I want to apply function fade()
as the onclick
event of every element of class circle
, in such a way that whenever a circle is clicked, it fades out.
However, the code above does not work at all. JavaScript console gives me the following error:
Uncaught TypeError: Cannot read property 'style' of undefined
I'm not sure what I am doing wrong, I'm just learning Javascript. I have searched for this specific error, but found nothing very helpful.
--Edit--
My actual code is not long, so here it is:
function fade(element) {
var o = 1.0;
var x = setInterval(function() {
element.style.opacity = o;
o -= 0.01;
if (o <= 0) {
element.style.display = "none";
clearInterval(x);
}
}, 10);
}
.circle {
height: 200px;
width: 200px;
border-radius: 50%;
content: '';
float: left;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
<div id="red" class="circle red"></div>
<div id="blue" class="circle blue"></div>
<div id="green" class="circle green"></div>
<script type="text/javascript">
var el = document.getElementsByClassName("circle");
console.log(el[0]);
for (var i = 0; i < el.length; i++) {
el[i].onclick = function() {
fade(el[i]);
}
}
</script>