teafields teafields - 7 months ago 11
Javascript Question

How can I set the color of the page (body) to the variable color of an element loaded in with AJAX?

I'd like to sync a container's background color to its child. Thanks

Here's what I tried, doesn't work...

<script>
$(document).ready(function() {
var color = $("section").css( "background-color" );
$('body').css("background-color", color);
});
</script>


Here's my Jquery AJAX:

<script type="text/javascript">
function getPage(id) {
$('#output').html('<img class="loader" src="/assets/img/loader.gif" />');
jQuery.ajax({
url: "get_page.php",
data:'id='+id,
type: "POST",
;}
});
}
getPage(1);
</script>


And my html...

<body>
<div id="output">
<section style=";">
<p>Bla bla bla</p>
</section>
</div>
</body>


And the working solution from Shomz's answer!>

<script type="text/javascript">
$(document).ready(function() {
updateColor();
});

function getPage(id) {
$('#output').html('<img class="loader" src="/assets/img/loader.gif" />');
jQuery.ajax({
url: "get_page.php",
data:'id='+id,
type: "POST",
success:function(data){$('#output').html(data);updateColor();}
});
}
function updateColor(){
var color = $("section").css( "background-color" );
$('body').css("background-color", color);
}
getPage(1);
</script>

Answer

You can call the color change code you call in the document ready callback in the AJAX success callback as well. Ideally, you could turn it into a function, and call it like that:

$(document).ready(function() {
    updateColor();
});

function getPage(id) {
$('#output').html('<img class="loader" src="/assets/img/loader.gif" />');
    jQuery.ajax({
        url: "get_page.php",
        data:'id='+id,
        type: "POST",
        }
    })
    .done(function(){
        updateColor();
    }
    // or just .done(updateColor)
}

function updateColor(){
    var color = $("section").css( "background-color" );
    $('body').css("background-color", color);
}

I don't see the code where you're updating your HTML from the AJAX response data, but I assume that's all good and your new section has a background color defined.