Javascript DOM CSS Style backgroundAttachment Property toggle

Introduction

Toggle between scroll and fixed:

Try to to resize the window if the scrollbar is not available.

Click the button to toggle between scroll and fixed position.

Scroll the page before and after you have clicked the button.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
body {/*from ww w.j  a  v a2 s  .  com*/
  background: #f3f3f3 url('background1.png') no-repeat fixed right top;
}
</style>
</head>
<body>

<h1>Hello World!</h1>

<button id="toggle" onclick="myFunction();">Set bg image to scroll</button>

<p>Some text to enable scrolling..
<br><br><br><br>
Some text to enable scrolling..
<br><br><br><br>
Some text to enable scrolling..
<br><br><br><br>
Some text to enable scrolling..
<br><br><br><br>
Some text to enable scrolling..
<br><br><br><br>
Some text to enable scrolling..
<br><br><br><br>
Some text to enable scrolling..
<br><br><br><br>
Some text to enable scrolling..
<br><br><br><br>
Some text to enable scrolling..
<br><br><br><br>
Some text to enable scrolling..
<br><br><br><br>
Some text to enable scrolling..
<br><br><br><br>
</p>

<script>
function myFunction() {
  var x = document.body.style.backgroundAttachment;
  document.getElementById("toggle").innerHTML=(x=="scroll")? "Set bg image to scroll!":"Set bg image to fixed!";
  document.body.style.backgroundAttachment=(x=="scroll")? "fixed":"scroll";
}
</script>

</body>
</html>



PreviousNext

Related