Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7489343
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T15:14:00+00:00 2026-05-29T15:14:00+00:00

What’s the best way to handle binding events on elements that will be refreshed

  • 0

What’s the best way to handle binding events on elements that will be refreshed with AJAX?

Is it better to use $(selector).live or similar methods for delegating events (on and delegate), or is it better to just re-bind the event handlers in $.ajax callbacks or $(document).ajaxComplete instead?

For the simple case, $(selector).live or equivalent works great, and seems like the right answer.

The tricky part is what to do inside a custom plug-in, where I’m creating a whole bunch of event handlers. I start running into problems in more complex cases where I want to register a handler on some other element that affects the one referenced by this.

For example, see jsFiddle: http://jsfiddle.net/f6QSY/2/

$.fn.myPlugin = function() {
    $input = this;
    var origSelector = this.selector;

    $(document).on("click", "a#trigger1", function() {
        $input.val('set from trigger 1');
    });
    $(document).on("click", "a#trigger2", function() {
        $(origSelector).val('set from trigger 2');
    });
}

$("input#newInput").myPlugin();
$("#wrapper").append("<input type='text' id='newInput'>");

<div id="wrapper">
  <a href="#" id="trigger1">Trigger 1</a>
  <a href="#" id="trigger2">Trigger 2</a>
</div>

In this code, the plugin is called on an input that is added dynamically and doesn’t exist yet (or is replaced via AJAX). The plugin sets up listeners on different elements that then impact the value of the input.

The trigger1 link doesn’t work because $input refers to a jQuery object with a selector that returned no elements at the time it was bound. The trigger2 link does work, by backing out the original selector for the input with this.selector and creating a new, fresh jQuery object in the event listener.

Is this approach of backing out the selector safe, or should I just call myPlugin again after updating the DOM?

My back-end is Java/JSF/PrimeFaces although that doesn’t matter too much.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T15:14:01+00:00Added an answer on May 29, 2026 at 3:14 pm

    “Better” is a loaded qualifier. Better in terms of what?

    I will always choose delegation (using .on())… where the listener is the nearest non-destroyed/replaced ancestor of any Ajax elements that need event binding.

    It’s possibly not ALWAYS going to be the most efficient in terms of computational cycles… a lot depends on the structure of your page and just how close that ancestor is. But it’s way way simpler to manage and decouples your Ajax call from your event binding.

    To me, that’s “better”.

    Sometimes what’s needed is not a direct answer to “how can I get my approach to work” but rather, a suggestion on how to tweak or retool your approach. In this case, I think caching a string of this.selector is creating a tight coupling where there doesn’t need to be one. Use classes, take advantage of DOM traversal (instead of IDs), and you will have a more re-usable product!

    [update follows]

    Not knowing exactly what your end goal is, here’s a pretty faked-up example of how I approach this sort of binding.

    Full Fiddle: http://jsfiddle.net/QpXpD/2/

    Reduced sample HTML:

    <div id="wrapper">
      <div class="foo clickable">
        <p>This is foo0.</p>
        <p class="info">Some info</p>
      </div>
      <div class="foo clickable">
        <p>This is foo1.</p>
        <p class="info">Some info</p>
      </div>
    </div>
    

    CSS:

    .highlight { background-color: yellow; }
    .info { display: none }
    

    Reduced sample JS:

    $.fn.myPlugin = function() {
        this.on('click', '.clickable', function() {
            $this = $(this);
            $this.toggleClass('highlight');
            $this.find('.info').slideToggle();
        });
    }
    
    $('#wrapper').myPlugin();
    

    The plugin executes on an element which is an ancestor element that I will never destroy and which is expected to contain my clickable elements.

    In the sample, the plugin is set to listen on #wrapper for any clicks on any element that has the clickable class. Now it doesn’t matter if I remove anything from the DOM or add new elements to that listening container… if I click and the element has the class clickable the function will execute. I do the find() in the context of the click, not the context of the full document or any stored selector names. I’m clicking something, and I want to look inside of it for something else.

    Again, I don’t know what your end goal is with your finds, etc. But hopefully this helps illustrate how to use .on() to avoid re-binding event handlers.

    [update 2]

    The sample is still somewhat convoluted — it’s not clear why the input has to be added dynamically, or why you don’t just reverse the order of adding and then calling the plugin (it would then work!).

    There is also too much of a reliance on element IDs. For something to be re-usable in a worthwhile way, you’re better off using classes. Here’s an update to your fiddle:

    http://jsfiddle.net/f6QSY/4/

    The triggers now have a class “trigger” (the ID is never used now).

    the JS part:

    $.fn.myPlugin = function() {
        // this is #wrapper because that's the selector that calls it in this sample
        this.on("click", ".trigger", function() {
            var $this = $(this); // this is now the element that was clicked
            var $input = $this.siblings('input'); // the first sibling input of a trigger
            $input.val('set from ' + $this.attr('id'));
            return false;
        });
    }
    
    $("#wrapper").append("<input type='text' id='newInput'>");
    $("#wrapper").myPlugin();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I am trying to understand how to use SyndicationItem to display feed which is
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I want use html5's new tag to play a wav file (currently only supported
I am doing a simple coin flipping experiment for class that involves flipping a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.