Marcus Christiansen - 1 year ago 97
HTML Question

Maximum Call Stack Exceeded

I'm writing javascript which fetches the users GPS coordinates (once) then calculates the distance between him/her and the a list of restaurants I'm displaying on the page.

``````\$(document).bind("DOMNodeInserted", function(e) {

if(\$('#user-gps').length) {

\$('.restaurant').each(function(index, value) {
var lat = \$(value).find('.latitude').attr('data-src');
var long = \$(value).find('.longitude').attr('data-src');

var distance = geolocator.calcDistance({
from: {
latitude: \$('#user-gps').attr('lat'),
longitude: \$('#user-gps').attr('long')
},
to: {
latitude: lat,
longitude: long
},
formula: geolocator.DistanceFormula.HAVERSINE,
unitSystem: geolocator.UnitSystem.METRIC
});

var string = Math.round(distance * 10) / 10 + "km";
var restaurantTitle = '#restaurant-' + index + ' .restaurant-title';
//\$(restaurantTitle).append(string);
//
console.log(\$(restaurantTitle));

//console.log(\$(value).find('.restaurant-title').text() + " - " + Math.round(distance, -1) + "km");
\$(restaurantTitle).append('<span>' + string + '</span>');
});
}

});
``````

I'm looping through each restaurant and calculating the distance, after which I format the string to display a value like 3.2km. I then want to append this in the DOM.

``````\$(restaurantTitle).append('<span>' + string + '</span>');
``````

As soon as I try this I get a Maximum Call Stack Exceeded error in the console.

I have tried several ways to make sure I'm only selecting the element I'm currently iterating over. I have even given each .restaurant a unique ID. The selector works perfectly fine but I cannot append or in any way add the string without getting the error.

Any help is much appreciated.

You've bound this to the `DOMNodeInserted` event on the `document` level, and when you insert the span you're inserting a DOM Node, triggering that event, which in turn inserts a span, that triggers the `DOMNodeInserted` event, that inserts a span that triggers ... and on it goes, until the stack is full.