0

I want to add an event handler to a dynamically generated list. I need to prevent the default action on the list item, and just console log "clicked". An example of what I'm trying to do is below:

$("#make-list").click(function() {
    var mainList = document.getElementById("the-list");
    for(var i = 0; i < 6; i++) {
        mainList.innerHTML += "<li class='list-item'><a class='the-list__link' href='https://example.com'>Click ME!</a></li>"
    };
})

$(".the-list__link").on("click", function() {
    e.preventDefault();
    console.log("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="make-list">MAKE LIST</button>
<ul id="the-list"></ul>

These answers:

Explain that due to how the .click() event is delegated, to use .on() method. I'm doing that. Why is it not working?

Sébastien
  • 11,860
  • 11
  • 58
  • 78
kawnah
  • 3,204
  • 8
  • 53
  • 103

2 Answers2

2
  1. You are not actually delegating the click (should be $("#the-list").on("click", '.the-list__link')
  2. You forgot to pass the event to the function that does e.preventDefault();

$("#make-list").click(function() {
  var mainList = document.getElementById("the-list");
  for(var i = 0; i < 6; i++) {
    mainList.innerHTML += "<li class='list-item'><a class='the-list__link' href='https://example.com'>Click ME!</a></li>"
  };
})

$("#the-list").on("click", '.the-list__link', function(e) {
  e.preventDefault();
  console.log("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="make-list">MAKE LIST</button>
<ul id="the-list"></ul>
Sébastien
  • 11,860
  • 11
  • 58
  • 78
  • I read the answers I posted closer - I missed that you needed to target the parent. I thought `.on()` would just target the links with the way I was doing it. – kawnah Mar 02 '18 at 19:02
1

delegate from existing element like body or the-list. example

$("#the-list").on("click", ".the-list__link", function(e) {
  e.preventDefault();
  console.log("click");
});
No one
  • 1,130
  • 1
  • 11
  • 21