Event delegation, links not working

Event delegation, links not working

EmilBr78EmilBr78 Posts: 6Questions: 2Answers: 0

Hi!

Sorry for asking a real noob question that I know has been asked before but I really can't get things to work...:(

The problem is that some links stop working on the pages after the one with datatables. I've understood that it's because of "event delegation", but I don't understand jQuery...

Here's the code I'm trying to use, I suspect some kind of syntax error and as you can see I tried to fix it but I basically have no idea what I'm doing...Everything works fine except for the links:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="/shop/26180/files/datatables/DataTables-1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){ $('#datatable').DataTable(); });
$('#datatable').on('click', 'a.edit', function (e) {
e.preventDefault();
});
</script>
<table id="datatable" class="display" style="width: 100%;">
//etc...

Thanks!
/Emil

Answers

  • allanallan Posts: 63,214Questions: 1Answers: 10,415 Site admin

    Hi Emil,

    Move your client event listener inside the $(document).ready( function () {.... At the moment it is running before the #datatable element is in the document.

    Allan

  • EmilBr78EmilBr78 Posts: 6Questions: 2Answers: 0

    Thank you Allan for the quick response! Unfortunatly you have to talk to me like I'm 200 years old, because I don't really understand :(

    I managed to solve the problem though. Apparently there were two different versions of jQuery that was the problem. Here's what the new code looks like which seem to work, but maybe it's still wrong?

    <script src="/shop/26180/files/datatables/DataTables-1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
    <script>
    $(document).ready(function(){ $('#datatable').DataTable(); });
    </script>
    <table id="datatable" class="display" style="width: 100%;">
    //etc
    
This discussion has been closed.