Reputation: 19969
I have the following:
<div class='outer'>
outside these values
<div data-which-price="special">
special price
</div>
<div data-which-price="regular">
regular price
</div>
</div>
I want to capture the click for outer BUT if they click within a data-which-price, I'd like to capture that. I'm not sure how to do this though. I have (bin at http://jsbin.com/capet/3/ ):
$('body').on('click','.outer', function(){
var which_price_val=$(this).attr('data-which-price');
console.log('here i am');
if(which_price_val){
console.log('price is: ' + which_price_val);
}
});
but this isn't doing it. How can I do this?
Upvotes: 1
Views: 52
Reputation: 2857
If you apply event in parent div, I'll be applied in the child div as well, so if you click on outer class or data-which-price same function onClick will be called. But if you want to call separate function to call on child click you have to do the following:-
$(document).ready(function(){
$('body').on('click','.outer', function(e){
console.log("clicked outer")
});
});
$(document).ready(function(){
$('body').on('click','[data-which-price="regular"]', function(e){
e.stopPropagation();
console.log("clicked inner")
});
});
Upvotes: 0
Reputation:
The second parameter of the jQuery on
method allows for a comma-delimited list of matching elements, so
$('body').on('click','.outer, [data-which-price]',
for the second element will give you what you need.
Upvotes: 1