I have this html:
<ul class='loc-list'>
<li id="where_7" class="cont-list">North America
<ul>
<li id="contry_114" class="contry-list">canada</li>
<li id="contry_115" class="contry-list">mexico</li>
<li id="contry_117" class="contry-list">united states</li>
</ul>
</li>
</ul>
Now I have written two jquery functions onclick of list as:
1st:
$(".cont-list").on("click", function(event){
alert("clicked on continent's list"); // working fine
};
2nd:
$(".contry-list").on("click", function(event){
alert("clicked on country's list"); // not working!
};
Here when I click on cont-list it get called ones as it should , but in the 2nd function it is not getting called instead it 1st function get called!
Is is because of it being an inner list? If so, then how to deal with this so that it will be called only when clicked on that list only?
Thanks in advance!
That's because events bubble up, you can use stopPropagation
method of the event
object:
$(".contry-list").on("click", function(event){
event.stopPropagation();
alert("clicked on country's list");
});
If you are generating the li
elements dynamically you should delegate the event:
$(document).on('click', '.coutry-list', function(){
console.log('li element is clicked');
})