Add value to 'style.width' attribute

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bugboy
    New Member
    • Sep 2007
    • 160

    Add value to 'style.width' attribute

    Hi, I'm trying to add a number to the width of an element but the width value doesn't seem to be numeric even after i remove the "px" from it.

    How can i add to an existing width? Below is my stab at it but i get 200200px instead of 400px.

    Thanks!

    Code:
    <?php
    echo'<div id="element"  style="width:200px;">';
    $w = 200;
    echo'<script type="text/javascript"> 
    	var w = document.getElementById("element").style.width;
    	w = w.replace(/px/, "");
    	w = w + '.$w.'+ "px";
    	document.getElementById("element").style.width = w;
    </script>';
    ?>
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Use parseInt() to get the integer value.

    In this case, why not use PHP to set the width directly instead of using JavaScript?

    Comment

    • bugboy
      New Member
      • Sep 2007
      • 160

      #3
      Thanks, That's what i'm looking for!

      I'm changing the width of a container that holds several divs arranged like colunms. I'm adding additional div's/columns to the container with ajax while trying to keep them horizontally aligned, so, the container needs to expand to fit them in otherwise they will be offset vertically.

      Here's my thinking.. If i were to update the entire container from the server then i would have to also update all of it's contents which could be 300kb+. By just adding the new content and then adjusting the container client side it saves resending the data for the existing content from the server every time i add a new div to the container. I suppose i could hold the content client side and re render it.. but it seems simpler to just adjust the container width with js.

      Am i right to do it this way?

      Thanks again.

      bugboy

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        I based my observation on the code you posted:
        Code:
        <?php
        echo'<div id="element"  style="width:200px;">';
        $w = 200;
        echo'<script type="text/javascript"> 
        	var w = document.getElementById("element").style.width;
        	w = w.replace(/px/, "");
        	w = w + '.$w.'+ "px";
        	document.getElementById("element").style.width = w;
        </script>';
        ?>
        which could simply be replaced with:
        Code:
        echo '<div id="element"  style="width:400px;">';

        Comment

        • hsriat
          Recognized Expert Top Contributor
          • Jan 2008
          • 1653

          #5
          Code:
          echo'<div id="element"  style="width:', (200 + $w) , 'px;">';

          Comment

          Working...