Sachin
Sachin

Reputation: 1003

jQuery, Dynamic on | accessing dynamic targets

How to access the dynamic targets when using jQuery.fn.on with dynamic selectors?

Because $(this) is giving the parent element inside binder function. And I need to get each element itself to fetch corresponding data-attributes dynamically.

Fiddle: https://jsfiddle.net/u1kuufj7/1/

HTML:

<div id="container">
  <div id="1" class="ch">Click</div><br>
  <div id="2" class="ch">Click</div><br>
  <div id="3" class="ch">Click</div><br>
  <div id="4" class="ch">Click</div><br>
  <div id="5" class="ch">Click</div><br>
</div>

Javascript:

var $container = $('#container');
var $chs = $('.ch');

$container.on('click', $chs, function() {
    alert($(this).attr('id'));
});

Upvotes: 0

Views: 29

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

To use event delegation, the second argument to on should be a selector (a string), not a jQuery object:

var $container = $('#container');
var $chs = '.ch';                   // <== Changed

$container.on('click', $chs, function() {
    alert($(this).attr('id'));
});

Now, this will refer to the .ch that was clicked.

Live Example:

var $container = $('#container');
var $chs = '.ch';

$container.on('click', $chs, function() {
    alert($(this).attr('id'));
});
<div id="container">
  <div id="1" class="ch">Click</div><br>
  <div id="2" class="ch">Click</div><br>
  <div id="3" class="ch">Click</div><br>
  <div id="4" class="ch">Click</div><br>
  <div id="5" class="ch">Click</div><br>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


Side note: $(this).attr("id") is just a long way to write this.id.

Side note 2: While id values starting with digits are perfectly valid, they're awkward to work with in CSS, since ID selectors can't start with a literal digit. (There are ways around it, via escaping or via attribute selectors, but it's awkward.) For that reason, I usually avoid ids starting with digits.

Upvotes: 1

Adam Azad
Adam Azad

Reputation: 11297

Use, you're passing a jQuery object to .on()

var $container = $('#container');
$container.on('click', '.ch', function() {
    alert($(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="container">
  <div id="1" class="ch">Click</div><br>
  <div id="2" class="ch">Click</div><br>
  <div id="3" class="ch">Click</div><br>
  <div id="4" class="ch">Click</div><br>
  <div id="5" class="ch">Click</div><br>
</div>

Upvotes: 1

Related Questions