How to register events handler after the page load?

I hope I'm making the question clear.

Say you have some check-boxes (or any other type of element for that matter) for which you register events handler when the page loads. Then you add some more check-boxes using AJAX (so no page reload). But you also want these newly added check-boxes (after the page was loaded) to have the same registered events handlers?

What I tried was this but I feel there has to be a better approach:

$(document).ready(function () {

  // Register custom envets handler
  registerCustomEventHandlers();

  $('a').on('click', addExtraFields);
});

function registerCustomEventHandlers() {
  $('input.class_name').on("change", sayHelloWorld);
}

function sayHelloWorld() {
  alert('Hello world');
}

function addExtraFields() {
  // insert some checkboxes...

  // register the events handler again for the newly added fields
  registerCustomEventHandlers();
}

So basically inside the function that adds the check-boxes I register again all the events handlers. I was looking at something like this $(document).change(function() {}); but apperently it is not supported by all browsers...

Any suggestions?

Answers:

Answer

You can delegate the event to the document instead so that they will be applied to all future inputs as well. You don’t even need to put it in a domReady event, since the document is always available:

$(document).on("change", "input.class_name", sayHelloWorld);

function sayHelloWorld() {
    alert('Hello world');
}

function addExtraFields() {
    // insert some checkboxes, they will have the same handler attached when inserted
}

Demo: http://jsfiddle.net/gdX3R/1/

Answer

I would recommend against using live selectors because of these reasons

Shortly summed up, it's a performance issue because it messes with every click event.

Instead, just use delegate like described in the post on lowest common parent element of the inputs (most likely a form):

$('#yourFormId').delegate('.class_name', 'click', function() { 
   // what you want to do
});

You can find a jsfiddle here

And don't use selectors like input.class_name (unless there elements other than input with that class name). They're slower than .class_name because they're looping through all the inputs in the form searching for elements with that class rather than just selecting by class.

Answer

As of jquery 1.4 you can always use live() too http://api.jquery.com/live/ which allows you to attach handlers now and in the future to any matching elements.

Answer

the way this is done in Jquery is such that you don't need the object to be present when creating the handler.

You could use:

$(document.body).on("click", "input[type='checkbox']", 
   function(){alert($(this))}
);

This will be applied to any new check-box added to the page, no matter timing.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.