Reputation: 24077
OK so I have a container div that loads some content which is generated by php. I don't know what the height of the content is and it is absolute positioned so the container div doesn't know how high to be until all the content is there. I collect the the height it needs to be in a php variable and want to use jquery to set the container div to this height but it's not working yet.
I have put this code near the bottom of the page:
<script type="text/javascript">
$(document).ready(function () {
$("#DynContainer").css({height:<?php echo $containerHeight; ?>px})
});
</script>
It is currently not working but looking at the code the php variable is echoed into it correctly. E.g:
<script type="text/javascript">
$(document).ready(function () {
$("#DynContainer").css({height:440px})
});
</script>
EDIT:
As many have helpfully suggested I needed to provide valid code for the CSS. I have since changed it to generate this code:
<script type="text/javascript">
$(document).ready(function () {
var containerHeight = "440px";
$("#DynContainer").css({height: containerHeight})
});
However it still doesn't work. The ID reference is deffo correct.
EDIT2:
Looking at the console I get this error:
[15:46:29.460] TypeError: $ is not a function @ http://localhost/serge/?page_id=2045:242
Suggesting jQuery is not loaded, but it's definitely called at the top of the page. Here is the whole page code: http://pastebin.com/tGadjaRA
SOLVED: it was a noconflict jQuery issue. Thanks everyone
Upvotes: 0
Views: 23869
Reputation: 12322
I'd recommend passing PHP variables to JS at the beginning of the script:
<script type="text/javascript">
var containerHeight = <?php echo $containerHeight; ?>;
// from now, it's pure JS. both better maintainable and readable
$(document).ready(function () {
$("#DynContainer").css({'height': containerHeight})
});
</script>
Upvotes: 0
Reputation: 38079
The "px" is resulting in invalid javascript. As other answers suggest, you can put quotes around it or you can remove the px completely:
$(document).ready(function () {
$("#DynContainer").css({height:<?php echo $containerHeight; ?>})
});
Upvotes: 0
Reputation: 92893
Put quotes around the value, since it's a string:
<script type="text/javascript">
$(document).ready(function () {
$("#DynContainer").css({height:'<?php echo $containerHeight; ?>px'})
});
</script>
http://jsfiddle.net/mblase75/GF3EK/
Alternatively, remove the "px" and the quotes so it's parsed as an integer ("px" is the default unit):
<script type="text/javascript">
$(document).ready(function () {
$("#DynContainer").css({height:<?php echo $containerHeight; ?>})
});
</script>
http://jsfiddle.net/mblase75/GF3EK/1/
Upvotes: 4