How to Enable & Disable Scrollbars With JavaScript
Scrollbars in a webpage can allow you to save screen real estate by allowing your readers to scroll within a <div> or similar element. Sometimes, however, these scrollbars can be unsightly rather than helpful. To give your readers the choice, add a button that toggles between enabling and disabling the scrollbars with one click.
Instructions
-
-
1
Open the webpage in an HTML editor or a text editor like Notepad (Microsoft Windows), TextEdit (Apple OSX) or pico (*nix systems).
-
2
Locate the document header, which begins with a "<head>" tag and ends with a closing "</head>" tag. On the line after the "<head>" tag, add a simple JavaScript function to enable and disable scrollbars:
<script type="Text/JavaScript">
<!--
function toggleScrollbar(el_id) {
if(document.getElementById(el_id).style.overflow=="hidden") { document.getElementById(el_id).style.overflow="scroll"; }
else { document.getElementById(el_id).style.overflow="hidden"; }
}
-->
</script>
-
-
3
Locate the element (such as a "<div>" or a form "<textarea>") and note its "id," defined by the attribute "id=" in the tag. If the element doesn't have an id already, add one, making sure that it is unique and not shared by any other elements on the page.
-
4
Add a new line after the element's closing tag with a div referencing the "toggleScrollbar()" function in an "onclick=" attribute:
<div onclick="toggleScrollbar('container')" style="border: 1px solid #000000;">Toggle Scrollbars</div>
Change 'container' to the id of the element with the scrollbars you want to hide.
-
5
Save and close the HTML document before opening it in a web browser. Click on "Toggle Scrollbars" to confirm that the scrollbar is being accurately hidden and shown.
-
1