简体   繁体   中英

make a div go off screen when a checkbox is unchecked in JavaScript

I'm trying to make a div go off screen when I uncheck a checkbox, it works fine when I check the box, but not when I uncheck it.

here is the JavaScript code:

function slide() {

    const button = document.getElementById('menucheck');
    const sidebar = document.getElementById('side');

    if (button.checked) {
        sidebar.style.left = 0;
    } else {
        sidebar.style.left = -250;
    }

}

The left style property needs units, not just a number:

sidebar.style.left = '-250px';

Example:

 function slide() { const button = document.getElementById('menucheck'); const sidebar = document.getElementById('side'); console.log(button.checked); if (button.checked) { sidebar.style.left = 0; } else { sidebar.style.left = '-250px'; } } document.querySelector('#menucheck').addEventListener('change', slide);
 div { position: absolute; left: -250px; }
 <input type="checkbox" id="menucheck" /> <div id="side">test</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM