1

Why is the link not working if the link is created with javascript? It only works if I make the link without the html() output

Not working

$(".link").on('click', function(){
    alert('Hello');
});

$("#link").html('<a href="#" class="link">Link</a>');

<div id="link"></div>

Working

$(".link").on('click', function(){
    alert('Hello');
});

<a href="#" class="link">Link</a>
Tushar
  • 85,780
  • 21
  • 159
  • 179
Stefan Frederiksen
  • 135
  • 2
  • 3
  • 15

2 Answers2

3

Your code doesn't work because event is bound when the element does not exists in DOM

  1. Wrap your code in ready or move the code to the bottom of body so your code will run when the DOM is completely parsed
  2. Use event delegation to bind event on dynamically created elements.(This will make the first option above optional)

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$(document).ready(function() {
  $("#link").on('click', '.link', function() {
    $("#link").append('<a href="#" class="link"> Link </a>');
  });

  $("#link").html('<a href="#" class="link">Link</a>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="link"></div>
Tushar
  • 85,780
  • 21
  • 159
  • 179
0

Change the order of the calls. The element with class of .link does not exist in the DOM yet when you attach the handler. You must add the link via the html call on the div before you can attach a handler to it with the on method. See below for a complete, working example.

$("#link").html('<a href="#" class="link">Link</a>');

$(".link").on('click', function(){
  alert('Hello');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="link"></div>
Drew Gaynor
  • 8,292
  • 5
  • 40
  • 53