In my html I have
<div id="map"></div>
#map {
width: 100%;
height: 100%;
background-color: #CCC;
}
that gets dynamically filled with several divs like the following
<div class="basicTiles1" style="left: 8128px; top: 8128px;"></div>
.basictiles1 {
position: absolute;
width: 64px;
height: 64px;
background-image: url(<snip urlToPng>);
background-position: 0px 0px;
}
Then an onmousedown event is added to #map like so
$('#map').on('mousedown', function(){console.log("mousedown");});
The event is never triggered. If I don’t add the tiles to the map, it works.
I tried doing it with jquery’s ‘on’, ‘onmousedown’, javascripts ‘addEventListener’.
The script doesn’t have any compilation errors. The event just doesn’t seem to trickle down.
Is it because the tiles are position absolute? Is it because they are added dynamically?
I understand that when you bind the event, the DIV’s are not there yet. Try using
delegateinstead, like this:EDIT: Elaborating
The jQuery
.on()reference states: “Attach an event handler function for one or more events to the selected elements.”Moreover, when you bind the event directly to your
#mapit will work as long as you don’t cover it with something else (you have to mousedown ON the actual #map element).The jQuery
.delegate()reference states instead: “Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.”Since you will be adding inner div’s -after- binding the event, this exactly fits what you want to do. Specifying the “div” selector actually binds mousedown to any (current or future) div inside #map. You could actually use
div.basictiles1if you have other, non-clickable divs there.