CancelImage Upload

How to set the CSS background-repeat Property Dynamically via JavaScript

On a dynamic website you may want to enable your users the ability of deciding for them selves whether or not background images should be repeated vertically, horizontally, both, or not at all. Here then is a quick tutorial on how to accomplish this task for the body property.

The key to the code example below of course is the JavaScript code:

<script language="JavaScript">

<!--
function repeatBody(repeat)
{

      document.body.style.backgroundRepeat = repeat;

}
-->

</script>

Any of the four above described options can be passed into the function repeatBody(), upon which the style property will be set via the above noted JavaScript style path. Here is a more complete example:

<html>
<head>
<title>How to set the CSS background-repeat Property Dynamically via JavaScript</title>

<style type="text/css">
<!--
body {
height:100%;
background-image: url(images/bg.jpg);
background-repeat: no-repeat;
}
-->
</style>

<script language="JavaScript">

<!--
function repeatBody(repeat)
{

      document.body.style.backgroundRepeat = repeat;

}
-->

</script>
</head>
<body>

<input type="button" onclick="javascript:repeatBody('repeat-y');" value="repeat-y">
<input type="button" onclick="javascript:repeatBody('repeat-x');" value="repeat-x">
<input type="button" onclick="javascript:repeatBody('repeat');" value="repeat">
<input type="button" onclick="javascript:repeatBody('no-repeat');" value="no-repeat">

</body>
</html>

The same outcome can of course be accomplished via getElementById():

<script language="JavaScript">

<!--
function repeatBody(repeat)
{

      document.getElementById("body").style.backgroundRepeat = repeat;

}
-->

</script>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com