tags:

views:

368

answers:

2

Hello!

I'm loading external page via jquery.ajax:

$("#mydiv").load("filter.html");

content of example.html:

<div id="filterdiv"><input id="filter" name="filter" size="40"/></div>

then I want to manipulate input#filter, so I wrote in javascript:

$('#filterdiv input').focus(function(){
    alert(Hello);
}

and nothing happens. If I paste a code of filter.html directly to a page, it works, but when I call it via ajax,

$('#filterdiv input').focus(function(){
    alert(Hello);
}

doesn't see ajax loaded content. Why do I do wrong? How can I manipulate ajax loaded html?

A: 

You need to apply the action 'after' the AJAX page is loaded. Which might mean adding it to the end of the AJAX page. Or on a callback function.

$("#mydiv").load("filter.html", null, function(){ $('#filterdiv input').focus(function(){
    alert("Hello");
} });

Unlike server-side programming pages, even if the page is currently fetching, the browser will continue to execute the next line of code. If you bind something (like click) on the next line, the page is probably not loaded, so it won't be bound.

The callback function on the other hand is only executed when the AJAX page is actually loaded.

Chacha102
Actually it loads after ajax page loaded, full code looks like:$(document).ready(function() { $("#mydiv").load("filter.html"); $('#filterdiv input').focus(function(){ alert(Hello);}});So do I need to transfer this part of code:$('#filterdiv input').focus(function(){ alert(Hello);} from index.html to filter.html?
Andersson83
just use the callback function I suggested.
Chacha102
Even though it occurs afterwards in the code, the call is asynchronous. This means that there is no guarantee that it will finish before the next statement adding the handler is executed. Putting it in the call back -- as shown-- will make sure that the element is loaded first.
tvanfosson
+1  A: 

You need to add the event handler after the html is loaded. Also note that I've quoted the alert parameter (not sure if that's really a problem or a typo in your question).

$("#mydiv").load("filter.html", null, function() {
   $("#filterDiv input").focus( function() {
      alert('Hello');
   });
});

If you were using one of the events that could be handled by the live method, you could have used that to set up your handler once for the entire life of the page. Unfortunately the focus event isn't one of those.

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.

Possible event values: click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup

Currently not supported: blur, focus, mouseenter, mouseleave, change, submit

tvanfosson