0

"Home" triggers the function but "Dynamic Link" doesn't.

<head>
<script>
window.onload = function()
{ 
var writeNav = writeNav + "<li class='nav-item'> <a class='nav-link' href='#'><span>Dynamic Link</span></a></li>"

$("#writeNav").append(writeNav);

};
</script>


<script>
    $(document).ready(function(){
        $('.nav-link').on("click", function(){
            alert('click function was called.');
        });
    });

</script>
</head>
<body>
<ul id="writeNav" class="navbar-nav mr-auto">
   <li class="nav-item">
      <a class="nav-link active" href="#">
          <span>Home</span>
       </a>
    </li>
</ul>
</body> 

it seems to write the same markup, but the .click() doesn't work for the appended item.

No idea why. Help?

  • the linked answer suggests the solution is using jQuery.fn.on, which it's already using, so i'm assuming something else is wrong? – Stephen Hoydis May 04 '20 at 19:18
  • @StephenHoydis You didn't read the answer completely. There are multiple ways to use on(), one method is for dynamically created elements. Also see https://api.jquery.com/on/#direct-and-delegated-events – j08691 May 04 '20 at 19:18
  • Got it. I was implementing this wrong. $('.nav-link').on("click", function(){ should have been: $(document).on('click', '.nav-link', function(){ and I needed to remove the "$(document).ready(function(){" part, which was stopping it from working once I had the other part implemented right. Thanks everybody! – Stephen Hoydis May 04 '20 at 19:22
  • Nothing wrong with `$(document).ready()` but you shouldn't use `window.onload` at the same time. – Guy Incognito May 04 '20 at 19:42

1 Answers1

0

You can solve that by adding a click event listener to the parent element, instead of adding it to the only existing elements, so each time a new element is added you need to add the event listener to it separately

var x = 1;
var navElement = document.querySelector("#writeNav");
document.querySelector("button").onclick = function() {
  navElement.innerHTML += `<li class='nav-item'> <a class='nav-link' href='#'><span>Dynamic Link${x++}</span></a></li>`;
}
navElement.onclick = function(e) {
  if(e.target.nodeName === "SPAN") {
    alert(e.target.textContent + ': click function was called.');
  }
}
<button>add Link</button>
<ul id="writeNav" class="navbar-nav mr-auto">
   <li class="nav-item">
      <a class="nav-link active" href="#">
          <span>Home</span>
       </a>
    </li>
</ul>
Saadi Toumi Fouad
  • 2,779
  • 2
  • 5
  • 18