7

does everybody know how to fix the problem of css after an Ajax request with $.load? For example, If I want to load just a DIV from a webpage, after my Ajax request with:

$('container').load('path_to_div #div_id');

I lose all the css and scripts that was associated with that div

Any idea please

user765368
  • 19,590
  • 27
  • 96
  • 167
  • 1
    By associated, you mean "inside" the div ( declared inside ) or you experience a problem where the style are no more applied and javascript event are unbinded ? – FMaz008 Feb 08 '12 at 14:32
  • 1
    styles and javascripts are no more applied – user765368 Feb 08 '12 at 14:33
  • 1
    It is probably because the styles that were applied to the other one no longer matched on the new element. Therefore they were disregarded. – Barry Chapman Feb 08 '12 at 14:34
  • 1
    Can you give us an example of the resulting HTML content after the ajax call, as well as the css rules that should be applied. – FMaz008 Feb 08 '12 at 14:34
  • 1
    @user765368 Were you able to resolve this issue? Could you please share the working solution? – Mrudang Vora Dec 04 '14 at 09:13

4 Answers4

2

I had that error the solution was :

$('#contentPagina').load(nombrePagina,function(){ $('#contentPagina').trigger('create'); });

Felipez
  • 468
  • 5
  • 6
2

Yes, any event handlers that were attached will be disconnected when content is replaced by AJAX. You can use jQuery's .on() or .live() as alternative event hooks to prevent this.

As for the CSS, you've probably got a class name or ID on the original content that's missing on the replaced content, or the replaced content does not match the same selectors you set up in your CSS.

Without seeing your HTML/CSS it's impossible to tell.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
2

Include all of the CSS for the element (and its children) in a CSS file that's included in the main page that you'll be loading it in to. So, if you have main.html, and you're loading the #div_id div into that page, you'll want to include the CSS for #div_id inside main.html.

You'll also want to include a script that can delegate event handlers, such as .delegate() (for versions of jQuery prior to 1.7) or .on() (for jQuery 1.7+), to the AJAX loaded content.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
1

You could load the CSS dynamically as in this answer, or add them to the page's CSS file that you're loading the div into.

As for the external scripts, $.getScript() should take care of your problem.

Community
  • 1
  • 1
Pat
  • 25,237
  • 6
  • 71
  • 68