0

I have a jquery code that gets json data and list them in a ul list. I want to populate this Items on click.

$('#places) is a ul list.

$.each(data, function (id, item) {                  
   $('#places').append('<a href="#" class="list-group-item" data-lat=' + item.lat + ' data-lng=' + item.lng + '>' + item.name + '</a>');      
}); 

Ul list items are links that included latitude and longitute values. I want to add click event to that links. Which I click link zoom to that location. How can add event?

Barmar
  • 741,623
  • 53
  • 500
  • 612
barteloma
  • 6,403
  • 14
  • 79
  • 173

2 Answers2

2

You can use on() to handle the dynamically generated link,

$('#places').on('click','a.list-group-item',function(e){
   e.preventDefault();
   //code here
});

You can use e.preventDefault(); for preventing browser default action.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 1
    you forgot something for it to work. (edit: yep thats it) – malifa Feb 03 '14 at 11:41
  • this returns "e" as x.Event {originalEvent: MouseEvent, type: "click", isDefaultPrevented: function, timeStamp: 1391427979506, jQuery110103376125982031226: true…} But I want use my Item object – barteloma Feb 03 '14 at 11:48
0

You can apply jquery click event on class "list-group-item"

$( ".list-group-item" ).click(function() {
var id = $(this).attr('id');//clicked <li> id
    var lat = $(this).attr('data-lat');//clicked <li> data-lat
    var lng = $(this).attr('data-lng');//clicked <li> data-lng
    //code for zooming 
});