Toggle between scroll and fixed for background image - Javascript CSS Style Property

Javascript examples for CSS Style Property:backgroundAttachment

Description

Toggle between scroll and fixed for background image

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
body {//from www.ja  v  a2  s. co m
    background: #f3f3f3 url('http://java2s.com/resources/a.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>test
<br><br><br><br>
test
<br><br><br><br>
test
<br><br><br><br>
test
<br><br><br><br>
test
<br><br><br><br>
test
<br><br><br><br>
test
<br><br><br><br>
test
<br><br><br><br>
test
<br><br><br><br>
test
<br><br><br><br>
test
<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>

Related Tutorials