Note that there are some explanatory texts on larger screens.

plurals
  1. POGoogle Maps addDomListener on div added by jQuery only sees last iteration of loop
    text
    copied!<p>I've got the following simple script:</p> <pre><code>var fruits = new Array("apple","orange","lemon"); $("#fruit_canvas").append("Mouse over these fruits:"); for(var i = 0; i &lt; fruits.length; i++) { var fruit = fruits[i]; var html = "&lt;div id='fruit" + i + "'&gt;" + fruit + "&lt;/div&gt;"; var fruitdiv = $(html); $("#fruit_canvas").append(fruitdiv); google.maps.event.addDomListener($(fruitdiv)[0], 'mouseover', function() { $("#result_canvas").append("Mouse over " + fruit); }); google.maps.event.addDomListener($(fruitdiv)[0], 'mouseout', function() { $("#result_canvas").empty(); }); } </code></pre> <p>It loops through a simple array, uses jQuery to make a div out of each element, and appends it to another div. A Google Maps DOM listener is then added to each appended div. That all works fine, but the DOM listener only seems to be aware of the last element of the array, i.e., it always returns "lemon" as the fruit, no matter which appended div you mouseover.</p> <p>To see what I mean, go to <a href="http://www.pinksy.co.uk/maptest.html" rel="nofollow noreferrer">http://www.pinksy.co.uk/maptest.html</a> and hover over each of the divs.</p> <p>I'm sure it's something obvious to do with how I'm passing the DOM element to the DOM listener, but I'm not sure how!</p> <p>I've also tried it without jQuery, but get the same results:</p> <pre><code>document.getElementById('fruit_canvas2').appendChild(document.createTextNode("Mouse over these fruits:")); for(var i = 0; i &lt; fruits.length; i++) { var fruit = fruits[i]; var div = document.createElement('div'); div.innerHTML = fruit; document.getElementById('fruit_canvas2').appendChild(div); google.maps.event.addDomListener(div, 'mouseover', function() { document.getElementById('result_canvas2').appendChild(document.createTextNode("Mouse over " + fruit)); }); google.maps.event.addDomListener(div, 'mouseout', function() { var cell = document.getElementById('result_canvas2'); if(cell.hasChildNodes()) { while(cell.childNodes.length &gt;= 1) { cell.removeChild(cell.firstChild); } } }); } </code></pre> <p>Thanks in advance... </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload