Skip to content

Instantly share code, notes, and snippets.

@khoand0000
Created December 3, 2015 20:14
Show Gist options
  • Save khoand0000/5c13d1dd7d2c9d7752eb to your computer and use it in GitHub Desktop.
Save khoand0000/5c13d1dd7d2c9d7752eb to your computer and use it in GitHub Desktop.
Using delegate() attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

Case: you have a <select>, when it is changed, creating new elements (example: <a>), and you want to handle click event of new <a>

<select id="chooser">
  <option value="1">Restaurants</option>
  <option value="2">Hotels</option>
</select>

<div id="result">
</div>

Solution 1: listen .click() event after new <a> elements are created

$('#chooser').change(function(e){
  var val = $(this).val();
  var result = getResult(val); // return array
  $.each(result, function(key, value) {
    $('#result').append($('<a href="#" class="shop-name">'+ value.name +'</a>'));
  });
  
  $('.shop-name').click(function(e) {
    // do something
  });
});

Solution 2: using .delegate() even no a.shop-name elements

$(document).delegate('.shop-name', 'click', function(event) {
  // do something
});

$('#chooser').change(function(e){
  var val = $(this).val();
  var result = getResult(val); // return array
  $.each(result, function(key, value) {
    $('#result').append($('<a href="#" class="shop-name">'+ value.name +'</a>'));
  });
  
});

ref: http://api.jquery.com/delegate/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment