WebDevDanno WebDevDanno - 2 months ago 16
jQuery Question

Click event / bind event not working in jQuery when generating buttons in Mustache JS

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
});

Answer

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);
   });
 }
Comments