Wednesday, 24 October 2007

Change the layer background color using a simple Javascript functions

These are two simple javascript functions that change on fly the background color of a layer without reload the page. To change the CSS background color with javascript we will use:

document.getElementById('ID').style.background ='background color'

Download this tutorial


1. Change background color
Copy and paste this code into <body> tag:

<script language="javascript">
function changeBg(idLayer){
idLayer_n = document.getElementById(idLayer);
if(idLayer_n.style.background!=''){
document.getElementById(idLayer).style.background ='#dedede';
document.getElementById('cb_text').innerHTML ='Changed! Click to restore';
} else {
document.getElementById(idLayer).style.background ='';
document.getElementById('cb_text').innerHTML ='Change Background color';
}
}
</script>

<div id='myLayer'>The script change the background color fo this layer!</div>
<a href="#" onclick="javascript:changeBg('myLayer')" id="cb_text">Change Background color</a>


2. Change background and text color with input field
This script change the layer background and text color using two input field to select the colors (esadecimal value).

To get the input field value with a javascript function we have to use:

document.getElementById('id').value;


Copy and paste this code into <body> tag:

<script language="javascript">
function changeBgInput(idLayer){
idLayer_n = document.getElementById(idLayer);
idColor_txt = document.getElementById('myColor_txt').value;
idColor_bg = document.getElementById('myColor_bg').value;
idLayer_n.style.color = idColor_txt;
idLayer_n.style.background = idColor_bg;
</script>

Text color: <br/>
<input type="text" id="myColor_txt" name="myColor_txt" value="#FFFFFF"><br/>
Background color: <br/>
<input type="text" id="myColor_bg" name="myColor_bg" value="#555555"><br/>
<a href="#" onClick="javascript:changeBgInput('myLayer');">Change text and background color</a>

No comments:

Post a Comment