Boboyum
Boboyum

Reputation: 708

How do I apply loaded javascript and css to .load() content?

I am loading .html content with jquery .load() but the javascript and css is not applied to the one.html/two.html after it is loaded by the .load() function.

Example below:

<head>
    <style> styles1 </style>
    <link href="stylesheets/style2.css" rel="stylesheet">
    <script src="script1.js">
    <script>     
        $(document).ready(function(){
           $("button.os").click(function(){
              fillmein = $(this).attr("target");
              fillmeinfile = $(this).attr("target")+'.html';
              $("."+fillmein).load("/contentfolder/"+fillmeinfile);
           });
        });

     ...
     other scripts
     ...
    </script>
</head>

<body>
   <p>the css and any js is applied to this block</p>
   <button class="os" target="one">replace</button>
   <div class="one">I will be replaced by one.html</div>
   <button class="os" target="two">replace</button>
   <div class="two">I will be replaced by two.html</div>
</body>

I understand that the one.html/two.html is loaded after the styles and javascript is loaded by the browser but how I get the styles and javascript that is in the <head> to apply to the newly loaded one.html/two.html?

I new to jQuery so let me know how I clarify if needed. thanks!

EDITED Thanks for providing answers everyone! Updated the code example to clarify what I meant.

copying the <style> and <script> into the one.html and two.html works but if I load the javascript twice it could conflict. for example, having logic that searches $(document), and functions that collapse and expand a section can be called multiple times. Is it possible to have the js and css that was loaded in the main page work on the newly loaded .html files or is there any clean and DRY way to do this?

Upvotes: 0

Views: 144

Answers (2)

mike510a
mike510a

Reputation: 2168

As suggested by Arun P Johny in his comment

You simply put your CSS inline on the target document and it will be automatically loaded along with the content.

Upvotes: 1

Pritish Vaidya
Pritish Vaidya

Reputation: 22189

You can write

$('button').on('click','Classname',function(){
  //write your structure here
  })

This will work for all tags with 'Classname',which are already present or dyanamically added later on.

Upvotes: 0

Related Questions