Home > other >  Use javacript to change a div width and move an inner div
Use javacript to change a div width and move an inner div

Time:11-26

I need to move a right-aligned div from one position to another using a button-powered javascript.

So the page is rendered and the outer div is a set width using position:relative;width:250px;. The inside div uses position:absolute;right:0px; to place it to the far right of the outer div.

I assumed that if my javascript set the width of the outer div it would change the outer div width and the inner div would move relatively to that. But it doesn't move (even though getting the width value of the outer div confirms that the new value was set).

Does this means that you cannot change div widths once the page has been rendered? As they can be changed if the browser window width changes I presumed this would be possible.

<div id="test" style="display:inline-block;position:relative;width:250px;">
    <div style="display:inline-block;">
        Some text
    </div>
    <div style="display:inline-block;position:absolute;right:0px;">
        Some more text
    </div>
</div>
<br>
<br>
<button type="button" onclick="resizeouter(500);">
    Move Right
</button>

<script>
function resizeouter(newsize){
    document.getElementById('test').width=newsize "px";
    //alert(document.getElementById('test').width);
}
</script>

I've tried with and without the "px".

JSFiddle

Thanks in advance.

CodePudding user response:

What you're looking for is style.width:

document.getElementById('test').style.width= newsize "px";

CodePudding user response:

You need to add .style.width

https://www.w3schools.com/jsref/prop_style_width.asp

function resizeouter(elementID, newsize){
  let div = document.getElementById(elementID); // current element
  let currentWidth = div.offsetWidth; // current width of your element
  let finalWidth = currentWidth   newsize; // addition of current width   newsize

  div.style.width=finalWidth "px"; // set the new width for this element 
  //alert(document.getElementById('test').width);
    
  // debug infos
  console.log(currentWidth   '   '   newsize   ' = '   finalWidth);
}
<div id="test" style="display:inline-block;position:relative;width:250px;">
    <div style="display:inline-block;">
        Some text
    </div>
    <div style="display:inline-block;position:absolute;right:0px;">
        Some more text
    </div>
</div>
<br>
<br>
<button type="button" onclick="resizeouter('test', 500);">
    Move Right
</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related