Javascript DOM CSS Style backgroundAttachment Property

Introduction

Set a background-image to be fixed (will not scroll):

document.body.style.backgroundAttachment = "fixed";

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

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 av  a2  s  .  c  o m
  background: #f3f3f3 url('background1.png') no-repeat right top;
}
</style>
</head>
<body>

<h1>Hello World!</h1>

<button onclick="myFunction()">Set background image to be fixed</button>
<br>

<script>
function myFunction() {
  document.body.style.backgroundAttachment = "fixed";
}
</script>

<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>
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>
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>

</body>
</html>

The backgroundAttachment property sets or gets whether a background image should scroll with the content, or be fixed.

Property Values

Value Description
scroll The background scrolls along with the element. Default
fixed The background is fixed with regard to the viewport
local The background scrolls along with the element's contents
initial Sets this property to its default value.
inherit Inherits this property from its parent element.

The backgroundAttachment property returns a String, representing how the background image is attached to the object within the document.




PreviousNext

Related