CSS : Implement with JavaScript

Change CSS style with JavaScript
JavaScript can control CSS with "style" attribute and set "ID" to HTML element that you want to change. One thing that use should know is CSS syntax may not the same JavaScript. For Example:" background-color: Red;" to control them with JavaScript you must to change to "backgroundColor = Red;"


Syntax JavaScript
document.getElementById("tagID").style.cssattribute = cssvalue;


Example (Change BGColor)

<script language="JavaScript">
     function ChangeBgColor(color) {
document.getElementById('testbody').style.backgroundColor = color;  } 
</script>
<body id="testbody"> <center><br><br> 
     <input type="button" value="Red" onclick="ChangeBgColor('Red');">
     <input type="button" value="Green" onclick="ChangeBgColor('Green');"> 
     </center>
</body>
Figure 1: Example Result


Example (Change Visibility and Display)


<script language="JavaScript">
function removeElement()
  document.getElementById("D1").style.display="none";
}
function changeVisibility()
  document.getElementById("D2").style.visibility="hidden";
}
function resetElement() {
  document.getElementById("D1").style.display="block";
  document.getElementById("D2").style.visibility="visible"; 
</script>


<div id="D1">Box 1<br /> <img src="test1.jpg" width="100" height="80"><br/>
<input type="button" onclick="removeElement()" value="Remove" /></div>
<div id="D2">Box 2<br /> <img src="test2.jpg" width="100" height="80"><br/>
<input class="box"  type="button" onclick="changeVisibility()" value="Hide" /></div>
<div>Box 3<br /> <img src="test.jpg" width="100" height="80"><br/>
<input type="button" onclick="resetElement()" value="Reset All" />



Figure 2: Example Result


CSS : Position << Previous Chapter


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...