Using JQuery Events on dynamically appended HTML

September 23, 2017 By - Irfan Dahir | 293

    JQuery has become one of our foundations of processing requests while staying on the same page. No refreshes, simple requests to your backend PHP scripts via AJAX and updating the DOM Modals.

    But often times, we’re met with a minor setback that leaves us pondering for hours. This is the second time that its happened to me and I decided to do something about it – write a blog post (how convenient, am i right?).

    Lets get started with your code jQuery event.

    $(‘.some_class’).on(‘click’, function() { … });

    This may work for the DOM that was given when your page loaded but it doesn’t do well for appended content. The fact that you’re possibly using .on for appending dynamically is half of your solution but there’s still one more step left.

     

    Fortunately, there’s a really quick fix for this. You need to rewrite it as:

    $(document).on(‘click’, ‘.some_class’, function() { … });

    Apparently jQuery now reads the DOM off the document, where it’s dynamically appended. Unfortunately, I have no idea why the previous method doesn’t work.

     

    RELATED READING

    blog user
    Irfan Dahir

    A college student living somewhere near the equator who's a programming, designing & a UX enthusiast; striving to master web + game development with interests also inclining towards machine learning, data science and other cutting edge stuff.

    Related Posts

    No Related Posts Found