3

I am new in AJAX. I have searched a lot on Internet but only got basic AJAX steps. Now I am writing codes using AJAX but a common problem I am facing continuously.

When I place return text in the particular id of HTML page, Javascript effects do not work. CSS works fine but Javascript effects like table sorting, jQuery effects or any other effect does not work. I know I am missing some concept here. But didn't get any effective answer.

Please suggest me what should I do? And what is the concept behind this...

César
  • 9,939
  • 6
  • 53
  • 74

2 Answers2

3

The new HTML you're adding to the DOM (page) didn't exist when your jquery ran the first time and bound events to elements on the page. You're probably using $("something").click(...) or .bind("click", ...). Instead of these use the delegate function from jquery. Delegate is generally more flexible and faster than live. For instance you can not stopPropagation in a 'live' binding.

Jquery Delegate

Why Delegate is better than Live

Here is another SO answer that explains the benefits of delegate

Community
  • 1
  • 1
kasdega
  • 18,396
  • 12
  • 45
  • 89
  • 1
    Actually, if you're using jQuery 1.7.x forward, `.on()` is preferred over `.delegate()` which is in the process of becoming deprecated. – Greg Pettit Nov 27 '11 at 06:04
0

What's most likely happening is that your events are getting unbound because you update the DOM with new elements. The easiest solution is to use the live method to bind to events : http://api.jquery.com/live/

Or you can simply rebind the events to the elements after insertion to the DOM just as easily.

EDIT

As user kasdega points out, another alternative is to use delegate : http://api.jquery.com/delegate/ Delegate works by using the bound root elements as the context to rebind events to DOM elements that may appear in the future.

JohnP
  • 49,507
  • 13
  • 108
  • 140
  • Thanks for a quick reply. I am visiting your link. Can you give me an example of your second solution of "rebind". Please if you can... – Abhimanyu Sharma Nov 27 '11 at 05:23
  • .live() can have problems and in general .delegate() is preferred. – kasdega Nov 27 '11 at 05:27
  • kasdega yup, delegate is another option. Added it, thanks. @abhimanyu what I meant was that you can simply rebind your events after you insert it into the DOM. This means that you'd have to make your plugin calls (tablesorter for example) anew once your DOM is updated. This depends on how you've designed you app since you'd need to group your init code together. – JohnP Nov 27 '11 at 05:32
  • `.on()` is preferred over `.delegate()` (per other comment to kasdega's answer) – Greg Pettit Nov 27 '11 at 06:04
  • is there any way to call all the required js functions automatically when DOM is updated. – Abhimanyu Sharma Nov 27 '11 at 06:14