Hello
I am trying to alert an array element on click - the array elements are randomly placed, however it is currently alerting “undefined”. I must be close to an answer but it is driving me crazy so I’m asking for a second pair of eyes please.
This is the JavaScript:
$(document).ready(function() {
var star = '<i class="fa fa-star" aria-hidden="true"></i>' // Define star to insert later
var starArray = ["Apple", "Pear", "Banana"]; // Define array
var section = $('#section-for-stars'); // Get id of section where stars are to be randomly places
var width =section.width(); // Get section width
var height = section.height(); // Get section height
for (var i=0; i<starArray.length;i++) { // for loop array.length output star onto .section-contact
var posx = Math.floor(Math.random()*width); // Define random position x
var posy = Math.floor(Math.random()*height); // Define random position y
//var styleCss = "position:absolute;"+"left:"+posx+'px;'+"top:"+posy+'px;
var div = document.createElement('div');
div.innerHTML = star;
var element = div.childNodes[0];
$(element).appendTo(section).css({ // Append
'position':'absolute',
'left':posx+'px',
'top':posy+'px',
});
}
$('i').click(function(e) {
var selected = (starArray[i]);
alert(selected);
});
});
This is a Codepen example - http://codepen.io/jameswinfield/pen/ObEgNJ
If anyone could tell me what I am missing that would be greatly appreciated.
James