0

I have a button which is generated in a function via a mustache JS template.

{{#attributes}}
    <a class="button--small btn" data-selector="{{selector}}">{{title}}</a>
{{/attributes}}

and a sample output of that is

<a class="button--small btn" data-selector=".news">More News</a>

However, I am trying to execute another jquery function when this button is clicked but regardless of whether I use .click(function() { }); or .bind it doesn't seem to work? Even a console.log doesn't print so I'm not getting into the right conditions.

Here is the script:

function lazyload(selector) {
    $("a[data-selector^='"+selector+"']").bind("click", function(e) {
            e.preventDefault();
            loadNews(selector);
    });
}

$(document).ready(function(){
   lazyload(".news"); // CALL FUNCTION READY FOR USAGE
});
WebDevDanno
  • 1,122
  • 2
  • 22
  • 50

1 Answers1

2

For newly created elements you need to delegate the event: see "Direct and delegated events" section.

function lazyload(selector) {
   $(document).on("click", "a[data-selector^='"+selector+"']", function(e) {
        e.preventDefault();
        loadNews(selector);
   });
 }
gaetanoM
  • 41,594
  • 6
  • 42
  • 61