Reputation: 841
I am using JavaScript to generate a map for a game, and each tile is a separate div. In order to be able to position the map on my site, I am throwing them all in another div.
So for example:
<div id="mapBox">
<div id="tile" ... ></div>
<div id="tile" ... ></div>
</div>
The #tile
divs are generated from data in an XML file, so they're dynamically generated. On each #tile
, I have an onmouseevent
that triggers a function (alert(1)
for now just to get it to work) but it never seems to be triggered.
If I put an onmouseevent
on #mapBox
it triggers it, but I can't get it to work for the #tile
divs.
Any help with this would be appreciated.
Upvotes: 1
Views: 417
Reputation: 195992
First problem, as mentioned, is that you use the same id for many elements, so the event only fires on the first one.
Secondly you should use the .delegate()
method on the #mapBox
after giving a class on the tiles like this
$('#mapBox').delegate('.tile', 'mouseover', function(e){
//do whatever here
})
example at http://jsfiddle.net/nXa27/1/
Update
Sorry, didn't see you were not talking about jquery..
Here is an example with pure javascript http://www.jsfiddle.net/AvJf7/
Still you will need to add a tile
class to your tiles for easy and valid selecting.
Upvotes: 0
Reputation: 322492
Not sure how you're selecting the #tile
divs, but it is not valid to have multiple elements with the same ID.
Selection using duplicate IDs will often give you only the first match (or some other unpredictable behavior).
When a duplicate identifier is needed, you should use a class instead of an ID.
<div id="mapBox">
<div class="tile" ... ></div>
<div class="tile" ... ></div>
</div>
Upvotes: 1