0

i have this html code, and i want to make the first div grab all the width when second div is made invisible, this works, however I wanted to know if it can be done in more graceful way in bootstrap 5.1:

<!DOCTYPE html>
<html>
<head>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
</head>
<body>
    <div class=container-fluid>
        <div class="row">
            <div id="canvas" class="w-75 border">
                <p>Hi there</p>
            </div>
            <div id="submenu" class="w-25 visible">
                <p>you there</p>
            </div>
        </div>
    </div>
    <button id="button1" type="button" class="btn btn-primary">Click</button>
    <script>
        const btn = document.getElementById('button1')
        const canvas = document.getElementById('canvas')
        const subMenu = document.getElementById('submenu')
        btn.addEventListener('click', ()=>{
            console.log('I am clicked')
            if(subMenu.classList.contains('visible')){
                canvas.classList.remove('w-75')
                canvas.classList.add('w-99')
                subMenu.classList.remove('visible')
                subMenu.classList.add('invisible')
                
            } else {
                canvas.classList.remove('w-99')
                canvas.classList.add('w-75')
                subMenu.classList.remove('invisible')
                subMenu.classList.add('visible')
            }
        })
    </script>
</body>
</html>
akaghzi
  • 27
  • 4

1 Answers1

1

You should use the columns instead of w-75, w-25. Then make the first column an auto-layout col so that it grows to fill the width when the other col is hidden. Also use d-none instead of visible...

<div class="container-fluid">
    <div class="row">
        <div id="canvas" class="col border">
            <p>Hi there</p>
        </div>
        <div id="submenu" class="col-3">
            <p>you there</p>
        </div>
    </div>
</div>

const btn = document.getElementById('button1')
const canvas = document.getElementById('canvas')
const subMenu = document.getElementById('submenu')
btn.addEventListener('click', () => {
    console.log('I am clicked')
    if (subMenu.classList.contains('d-none')) {
        subMenu.classList.remove('d-none')
    } else {
        subMenu.classList.add('d-none')
    }
})

https://codeply.com/p/VsC8j2BlF9

Also, it would be easier to use the Bootstrap collapse component. Then you don't need the extra JavaScript..

https://codeply.com/p/tBb263fzdp

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624