any idea why this jquery on click isn't working?

620 views javascript
-5

i'm trying to click a class with jquery in wordpress. Here is my code

import $ from 'jquery';

class Scroller{
constructor(){
    this.events();
}
events(){
    alert("hi");
    $(".load-more").on("click", this.test_func.bind(this));
}

test_func(){
    alert("yo");
}

when i run this code the alert for hi shows up, but then when i click .load-more nothing happens.

I know jquery is set up because when i run this js file (targetting the same class) instead, it works:

jQuery(document).ready( function($){

$(document).on('click','.load-more:not(.loading)', function(){

answered question

1 Answer

3

Maybe the input is not rendered the moment you try to add the handler. Try using this syntax to add you test_func click handler:

$(document).on('click','.load-more', this.test_func.bind(this));

If your element is dynamically added then the above is the only way the handler will be added properly to the click event due to Event Delegation. Read more here.

posted this

Have an answer?

JD

Please login first before posting an answer.