mohsin mohsin - 3 months ago 9
HTML Question

Styling to h1 or h2 element loaded by ajax in jquery not working

I am trying to load view files with ajax by clicking on two different links, those view files has h1 and h2 tags, I want to handle their style from one place.

Index file
--------------------------------
<div id='contentDiv' style="background:#98bf21; height:200px; width:800px; position:absolute; left:-100%; "> </div>
--------------------------------


index file loads the header

header file
--------------------------------
<li><a class='ajaxLoad' id='ajaxLoad1' href="link1" >First File</a></li>
<li><a class='ajaxLoad' id='ajaxLoad2' href="link2" >Second File</a></li>


<script>

$(document).ready(function(){

contDiv = $('#contentDiv');

$('a.ajaxLoad').on('click', function(e){
var href = $(this).attr('href'), position = '100px';

e.preventDefault();

contDiv.css('left','-100%');
contDiv.animate({left: position});
var loadDoc = contDiv.load(href);
var getDivId = '#'+loadDoc[0].id;
var getChild = $(getDivId).children().css({'color':'red'});

});
});

</script>
--------------------------------


loading the external file into contentDiv in index file.

File one contains

This is file 1



File two contains

This is file 2



I want to get the content of loaded file and style them,But I am getting this

[prevObject: e.fn.init[1]]


and content not loading properly.

Answer

The jQuery load method is asynchronous, so you have to use a callback to handle it upon completion:

$(document).ready(function(){       

  contDiv = $('#contentDiv');

  $('a.ajaxLoad').on('click', function(e){
var href = $(this).attr('href'), position = '100px';

e.preventDefault();

contDiv.css('left','-100%');
contDiv.animate({left: position});

// Changed code here
contDiv.load(href, function() {
  contDiv.children().css({'color':'red'});
});
// Changed code ends

   });
 });