I have the following code, this code runs when a person clicks a link. But I also need to load it initially when the person visits the page to load the default address. So after this code I have $(‘.viewmap’).click();
The problem is when I do that the click action is ran for each link with the class viewmap. Is it possible to have this code run once with mapid having the default value of 0 so I can reuse this function for both default loading of the map and then if someone clicked one of the links with the viewmap class? Or do I have to create separate functions? One for the default load and one for the click action?
$('.viewmap').click(function() {
var id = $('#id').text();
var mapid = $(this).attr('title');
$.ajax({
cache:false,
url:'path/to/script'
dataType:'json',
success: function(data) {
$('#currmap').gMap(
{
latitude : data.lat,
longitude : data.lon,
address : data.address,
maptype : 'ROADMAP',
zoom : 8,
markers:[{
latitude : data.lat,
longitude : data.lon,
address : data.address,
html : data.display
}]
}
);
}
});
});
Try putting the processing code in it’s own function. You can then call that directly on page load, and also when a click event happens on the element. Try this:
This then avoids having to manually trigger the click event on the elements which is what is causing your problem.