Reputation: 14334
I am attempting to implement an input element for geocoding without a button. i.e. the user begins to type in an address and then selects the wanted address from a list of Google suggested ones
In my Javsacript code, I load the following to enable the geocoding for my input element:
var geocoder = new google.maps.Geocoder;
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input);
This provides a set of dropdowns from the input field of potential addresses. When an address is selected by down arrow and then Enter is pressed, I use the following to capture the Enter key and perform the geocode (rather than using a button).
// capture enter on address input selection
$("#pac-input").keyup(function(e) {
if (e.keyCode == 13) {
geocode();
}
});
However, I would also like to capture the click of the mouse on one of the potential dropdown fields. I am using the following to capture all mouse clicks
// capture event for mouse click or ipad input
$(document).on('click', function(e) {
console.log($(this));
var target = $(e.target);
console.log(target[0]);
});
This function definitely works as I see console activity on mouse clicks, such as:
[document, context: document]
<input id="pac-input" class="form-control" type="text" placeholder="Enter a location" autocomplete="off">
However, on clicking one of the dropdown fields provided by the Google JS, I see no console log. What is happening here?
Edit: I do now see console output. But using
$(document).on('click', function(e) {
console.log($(this));
var target = e.target;
console.log(target);
});
I see <body role="document">..</body>
. Not much of an identifier..
Upvotes: 2
Views: 188
Reputation: 1220
Your target
is <body role="document">..</body>
because that's what you've attached the event handler to - $(document)
is all very well for trapping all mouse clicks, but it means the event has to bubble all the way up before getting handled.
Why not use the inbuilt event handler for Google's autocomplete
? From this example:
google.maps.event.addListener(autoComplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (place.geometry) {
map.panTo(place.geometry.location);
map.setZoom(15);
}
});
Upvotes: 1