Alert Array Element on Click


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
            $('i').click(function(e) {

    var selected = (starArray[i]);

This is a Codepen example -

If anyone could tell me what I am missing that would be greatly appreciated.


after your code run i will be the length of the array, and there is never an element at that index.

OK. I tried putting the click function inside the for loop but then I got 3 alerts for undefined instead.

same problem again. the click handler forms a closure that uses the variable i at runtime, where its value is the array length. plus you have definod the click handler three times.

Do I need to do a separate function?

there are various ways to do that.

  • save the text to display inside the element (data attributes)
  • break the closure (this needs wrapping the closure in an IIFE that is passed the value to use, essentially you change the variable that is closured)

Thanks for your response - I used data attributes in the end - I always forget they exist.

I replaced the click function with the below and it works.

          $(element).attr('data-number', i)
            $('i').click(function(e) {
    var number = $(this).attr('data-number');

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.