title: Global variable becoming undefined from within event listener - javascript
body: <p>I have a function that creates a new image and gives it an event listener, which needs to access a global variable. The global variable (_currentSection) is defined until it gets to the declaration of the event listener, when it then becomes undefined. Here is the function:</p>
  
  <pre><code>function relMouseCoords(event) {
      var totalOffsetX = 0;
      var totalOffsetY = 0;
      var canvasX = 0;
      var canvasY = 0;
      var currentElement = this;
  
      do {
          totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
          totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
      } while (currentElement = currentElement.offsetParent)
  
      canvasX = event.pageX - totalOffsetX;
      canvasY = event.pageY - totalOffsetY;
  
      //alert( 'x: ' + canvasX + '         y: ' + canvasY);
  
      for (var i = 0; i &lt; _currentSection.allHotSpots.length; i++) {
          if (canvasX &gt; _currentSection.allHotSpots[i].topLeft[0] &amp;&amp;
              canvasX &lt; _currentSection.allHotSpots[i].bottomRight[0] &amp;&amp;
              canvasY &gt; _currentSection.allHotSpots[i].topLeft[1] &amp;&amp;
              canvasY &lt; _currentSection.allHotSpots[i].bottomRight[1]) {
              //alert( 'x: ' + canvasX + '         y: ' + canvasY);
              if (_currentSection.allHotSpots[i].isPicZoom === "false") {
                  appendHotSpot(_currentSection.allHotSpots[i], _currentSection.thePicture, _context, true);
              } else {
                  picZoomCode = _currentSection.allHotSpots[i].myPicZoom;
                  var img = new Image();
                  img.onload = function() {
                      _context.drawImage(img, 0, 0, _canvas.width, _canvas.height);
                  }
                  img.src = "data:image/jpeg;base64," + _currentSection.allHotSpots[i].picture;
  
                  img.addEventListener('load', function() { 
                      if (_currentSection.allHotSpots[i].allHotSpots) {
                          for (var j = 0; j &lt; _currentSection.allHotSpots[i].allHotSpots.length; j++) {
                              appendHotSpot(_currentSection.allHotSpots[i].allHotSpots[j], _currentSection.allHotSpots[i].thePicture, _context, false)
                          }
                      }
                  }, false);
              }
          }
      }
  }
  HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;
  </code></pre>
  
  <p>So within img.addEventListener I need access to _currentSection, but it only just goes undefined in img.addEventListener. How do i keep it as being defined?</p>