-2

I have the following javascript code:

$(function (){
    $('a.folder').click(function() {
       // code goes here ...
    }
});

And the following html code:

<a class="folder" href="GetFilesAndFolders?rootFolder=Exigences">Etudes de cas</a>

Whenever I click on the link, the javascript code is never reached. I must say that this html code is generated dynamically after the page loaded. Is this the reason? Any workaround?

Bronzato
  • 9,438
  • 29
  • 120
  • 212

2 Answers2

2

when you attach the click handler it's possible that your anchor doesn't exist, try using this:

$(function (){
    $(document.body).on('click', 'a.folder', function() {
       // code goes here ...
    });
});

using this event delegation the click event will fire even if your anchor created dynamically after this code.

Shlomi Komemi
  • 5,445
  • 3
  • 28
  • 41
0

$(document).ready(function() {
  $("body").on("click", "a.folder", function(e) {
    e.preventDefault();
    alert('a .folder was clicked');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="folder" href="GetFilesAndFolders?rootFolder=Exigences">Etudes de cas</a>
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
indubitablee
  • 8,136
  • 2
  • 25
  • 49
  • dont answer on obvious dublicates – Alex Feb 09 '15 at 15:16
  • 1
    This is also wrong - the `a.folder` selector will not account for dynamically added elements. You'll need to bind to an element higher up in the hierarchy for that. Like so: `$("body").on("click, "a.folder", function() { });` – Dellkan Feb 09 '15 at 15:18