Setting the innerHTML of an element using a loop and closure

Viewed 158

I'm trying to solve a simple exercise with JavaScript closures in order to understand how they work and have come across an error which probably has a simple answer or may not be related to the closure itself.

The html markup i'm using is:

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<ol>
  <li class="track">Test Song</li>
  <li class="track">Test Song</li>
  <li class="track">Test Song</li> 
  <li class="track">Test Song</li>
  <li class="track">Test Song</li>
  <li class="track">Test Song</li>
  <li class="track">Test Song</li>
  <li class="track">Test Song</li>
  <li class="track">Test Song</li>

</ol>
  <p>Now playing track <span id="number"></span></p>
</body>
</html>

and the JavaScript is:

$( document ).ready(function(){

  var elNum = document.getElementById('number');
console.log(elNum);
function setUpClick(){

  var elTracks = document.getElementsByClassName('track');


  function clickHandler(){

    return function(track){
      elNum.innerHTML = track;
      };

  }

  for(var i = 0, l = elTracks.length; i < l; i++){
    elTracks[i].addEventListener('click', clickHandler(i));

  }


}
setUpClick();
});

The output I am getting on click is becoming [object MouseEvent] when it should be the actual track clicked. I'm not sure what is causing that, here is a fsfiddle: https://jsbin.com/gujomef/edit?html,js,output

1 Answers
Related