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

5
  • 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 ? Commented Feb 8, 2012 at 14:32
  • 1
    styles and javascripts are no more applied Commented Feb 8, 2012 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. Commented Feb 8, 2012 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. Commented Feb 8, 2012 at 14:34
  • 1
    @user765368 Were you able to resolve this issue? Could you please share the working solution? Commented Dec 4, 2014 at 9:13

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

2

I had that error the solution was :

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

1 Comment

I've been looking for this for an hour now.Thank you!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.