HOWTO #4 – Solve Javascript not working in AJAX loaded page problem

February 9, 2009

Filed under: ajax, jQuery, javascript — Estevão Mascarenhas @ 23:49

saved1

Many webdevelopers found a very boring error: Javascript don’t “see” elements in content loaded using AJAX method.
Let’s see how you can solve this problem.


Requirements

The Function

We will use the live() function, added in the lastest version of jQuery.
See the description:

Added in jQuery 1.3: Binds a handler to an event (like click) for all current – and future – matched element. Can also bind custom events.

How to use

Here you can see how to use this function, an example:

$("p").live("click", function(){
      $(this).after("<p>Another paragraph!</p>");
});

This will get all “p” tags and add an onclick javascript function to add another paragraph. You can see the live example here.

Using this function, the Javascript script will work in all elements added after the load of the script.
That’s it! See you in the next article. ;)

Share:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Technorati
  • DZone
  • Live
  • MySpace
  • Reddit

One Response to “HOWTO #4 – Solve Javascript not working in AJAX loaded page problem”

  1. Seu blog ta mt legal Soulz! E os tutoriais são mt bons, alguns eu n entendo ainda, mas whatever. :D

Leave a Reply




Powered by WordPress