0
<div class="card-block">something</div>
<div class="card-block">something</div>
<div class="card-block">something</div>
<div class="card-block">something</div>
<div class="card-block">something</div>

So, I have something like this in my code, I was wondering how do add a click function that grabs the specific div that was clicked?

I thought this would work $('.card-block').on('click', function() { "do something" });

Ok, so I guess I forgot to mention my DOM is being build dynamically, and it's constantly being built dynamically every time the user clicks on a button, or resizes the window.

Eric Chu
  • 1,599
  • 3
  • 17
  • 26

3 Answers3

1
$('.card-block').on('click', function() { var div = $(this); });

You can use this keyword to get clicked div. In case your element is added dynamically, then use this code:

$('body').on('click', '.card-block', function() { var div = $(this); });
Akshey Bhat
  • 7,901
  • 1
  • 18
  • 20
0

Your code should work, if it' doesn't it probably means that you're binding the click event when the element isn't there yet. Try to delegate the event to the body:

$('body').on('click', '.card-block', function(e) {
    var your_div = $(this);
});
Jonas Grumann
  • 10,058
  • 2
  • 18
  • 37
0

Use this. It will also attach click event for dynamically loaded elements having class card-block.

$(document).on('click','.card-block', function() { 
  var x = $(this);//It will be the appropriate div
});
AB Udhay
  • 633
  • 4
  • 9