views:

89

answers:

1

I have the following script that creates a div, adds a Google Maps DOM listener, and appends it to another div to another div using JavaScript's built-in DOM manipulation methods:

var div = document.createElement('div');
var html = '<b>' + string_of_text + '</b>';
div.innerHTML = html;
google.maps.event.addDomListener(div, 'click', function() {
    google.maps.event.trigger(marker, 'click');
});
document.getElementById('sidebar').appendChild(div);

So far, so good. When the page loads, the marker's click event is triggered by clicking the div.

However, when I try to accomplish the same thing with the following jQuery code the div is appended and everything loads, but no clicked event is triggered when clicking the div:

var div = $("<div><b>"+string_of_text+"</b></div>");
google.maps.event.addDomListener(div, 'click', function() {
    google.maps.event.trigger(marker, 'click');
});
$("#sidebar").append(div);

Is there a way to use jQuery to create a DOM element and give it a Google Maps DOM listener?

A: 

You need

google.maps.event.addDomListener(div[0], 'click', ...  // or div.get(0)

In order to pass the element, not the jQuery object. (see jQuery get)

Also you may wanted:

$("#sidebar").append(div);

instead of

$("#sidebar").append(sidebarEntry);

I don't know where sidebarEntry comes from.

galambalazs
Thanks, div.get(0) did it! div[0] caused my browser to complain about syntax. Also, "sidebarEntry" comes from a variable assignment that happens after the creation of the div in my original script. I simply forgot to change it to "div" for the purpose of my explanation.
Keyslinger
Well, I'm glad your problem is solved anyway! Cheers! :)
galambalazs
$(div)[0] does the trick.
Keyslinger