Which hook should I use?



  • I have written a plugin for parsing out some text in each post and replacing it with some HTML. Now I want to add event listeners to these HTML elements for when the user clicks on them.

    $(document).ready only works when the page is first loaded. I discovered that I have to use $(window).on('action:ajaxify.end', func) by browsing other plugins, but this only adds the listeners when navigating to the topic. If a user adds a new post or edits a post, the replaced HTML within that post will not be interactive (they cannot click on it).

    Which hook should I use for adding event listeners to edited posts or created posts?


  • Admin

    You can use event delegation with jquery.

    $('[component="topic"]').on('click', '[component="post/content"] .your-custom-class', function() {
        alert('your element clicked');
    });
    

    Then you don't have to add remove event listeners everytime posts are edited or loaded via infinite scroll.



  • Thank you @baris! I totally forgot about this. I've included my code for future reference.

    $(document).on('click', '.my-class', function() {
       // do stuff
    });
    

Log in to reply
 


Looks like your connection to NodeBB was lost, please wait while we try to reconnect.