DG3
DG3

Reputation: 5298

javascript within php

I am trying to do the following in jquery

<?php

    echo "<script>";
    echo "$(document).ready(function(){";
    echo "$('#mainbody-wrapper').removeClass('mainbody-wrapper')";
    echo ";";
    echo "$('#mainbody-wrapper').addClass('newStyle')";

    echo ";";
    echo "contentHeight=$('.content').css('height') + 20";
    echo ";";

    echo "alert(contentHeight)";
    echo ";";
    echo "$('#mainbody-wrapper').css('height',contentHeight)";
    echo ";";
    echo "$('#subcontent-wrapper').remove()";
    echo ";";
    echo "})";
    echo "</script>";

?>

But the variable contentHeight output 300px20. I want to do javascript addition, but its getting concatenated. How can this be achieved?

Upvotes: 2

Views: 136

Answers (3)

Dan F
Dan F

Reputation: 12051

If you just want to read the height, jquery has a height method

echo "contentHeight=$('.content').height() + 20";

From the doco:

The difference between .css('height') and .height() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element's height needs to be used in a mathematical calculation.

Upvotes: 3

Senica Gonzalez
Senica Gonzalez

Reputation: 8212

Do you need to echo everything? You know you can run php and javascript together in the same file.

for example:

<?php echo 'hello world'; ?>
<script>
jQuery("<?php echo $var; ?>").addClass("test");
</script>
<?php echo 'end'; ?>

Upvotes: 0

Ibu
Ibu

Reputation: 43850

You can use parseInt():

 echo "contentHeight= parseInt($('.content').css('height')) + 20";

also to go to the next line, use line breaks \n.

example:

echo "contentHeight= parseInt($('.content').css('height')) + 20;\n";

Upvotes: 1

Related Questions