1

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 () {
etarhan
  • 4,138
  • 2
  • 15
  • 29
Tintinabulator Zea
  • 2,617
  • 5
  • 18
  • 32

2 Answers2

1

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.

etarhan
  • 4,138
  • 2
  • 15
  • 29
1

That's because you told jQuery to attach the desired event to all of the current existing data. in other words - if you created the .load-more element after you declared of the event, jQuery will not attach the desired event to the desired selector.

You can go with 2 options:

    1. Create the element, and then add the event like you specified in your first example.
    1. Use $(document).on('click', '.load-more:not(.loading)', callback).
Eliya Cohen
  • 10,716
  • 13
  • 59
  • 116
  • Thank you, this works! I'm a little confused though. I don't create the element after the page is loaded. It's part of the html of the page. I also have an almost identical page for a different site where the $(".load-more") way works – Tintinabulator Zea Sep 16 '18 at 17:11
  • @TintinabulatorZea There can be some other reasons that may cause you this behavior. Although, I can't know exactly why it happens since you haven't presented the full code. – Eliya Cohen Sep 16 '18 at 17:18