0

I've read 3 answers to similar questions, but I wasn't able to apply them to my site. I'm loading html pages through ajax. I understand I can't apply a $("a").click() event during document.ready because the ajax content links don't exist in the dom yet. I thought about trying to add the events in the $.get response, but adding a $.get to a click inside a $.get seems like madness. My attempts to use $(document).on('click', 'a', fn()) are also not working.

$(document).ready(function() {

    $(document).on('click', 'a', function(e) {
      e.preventDefault();
      $.get($(this).attr("href"), function(data) {
        $("#mainSection").html(data);
      });
      return false;
    });
});

mainSection is a div id on index.html (same where this code is running). All links are processing as if normally clicked, with no script errors.

Joseph Schmidt
  • 119
  • 1
  • 10
  • Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – empiric Sep 29 '16 at 17:54
  • Thanks empiric! I actually tried to implement 6 different answers from that page & wasn't able to make it work :( – Joseph Schmidt Sep 29 '16 at 17:55
  • Can you set up an example (with html) to show how your markup looks like before and after ? – empiric Sep 29 '16 at 18:04

1 Answers1

0

There is no obvious error inside your code. Either your script is in wrong place, or you have error on other side, or something else.

Working example:

var content = $('.content');
var newAnchor = function() {
 content.append('<p><a href="https://google.com">' +  new Date().getTime() + '</a></p>')
}
$('button').on('click', newAnchor);
$(document).on('click', 'a', function(e) {
 e.preventDefault();
    alert('No-no!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content"></div>
<button>Add new anchor</button>

I suggest you put this script outside of dynamic content area #mainSection.

skobaljic
  • 9,379
  • 1
  • 25
  • 51