CodeDezk CodeDezk - 5 months ago 12
HTML Question

HTML hover button list click event child

I need to get the click event while the list clicked

Here is html code,

<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div id="myList" class="dropdown-content">
</div>
</div>


For click event

<script>
$('#myList').click(function(event){
event.stopPropagation();
alert(event.target.id);
});

</script>


And the list is filling from jason data

for(var i = 0; i < jsonStr.length; i++) {
var obj = jsonStr[i];
//console.log(obj);
var node = document.createElement("a");
var textnode = document.createTextNode(obj);
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}


Jason data

["live0.ts","2.mpg"]


But when clicked the list the event is not triggering.

Answer

Try this... your click event should be enclosed in the $(document).ready function

$(document).ready(function(){
$('#myList').click(function(event){
      event.stopPropagation();
      alert(event.target.id);
     });
});

explanation here: Why should $.click() be enclosed within $(document).ready()?