How to Change CSS Properties With Javascript
Cascading Style Sheets (CSS) creates the layout and colors visible on a Web page. Javascript is a client-side software used to program dynamic content on the page. Javascript can be used to manipulate CSS properties on your Web page controls. Javascript can change colors, images, styles and text in your CSS properties. This gives you the ability to change the Web page from user interaction.
Instructions
-
-
1
Open your HTML file in your favorite text editor. This can be a simple, free application such as Notepad. After opening the file, scroll down to the element you want to edit. In this example, a form button is edited.
-
2
Within the button form tag, enter the following code:
onClick="javascript:changeVisibility(this);"
The "onClick" event changes the CSS property when the user clicks the button. "changeVisibility" is a function you create to change the visibility property. Finally, the "this" notation sends the button object to the function, so it knows which button to change on the page. -
-
3
Scroll to the top of your HTML page to create the Javascript function. Within the "<head>" and "</head>" tags, enter the following Javascript tag entries:
<script type="text/javascript"> </script>
This denotes a block of Javascript code, so the HTML file has instructions to execute the commands instead of translating them to HTML. -
4
Use the following code to change the CSS property on your HTML element:
function changeVisibility(button)
{
button.style.visibility = "hidden"
}
In this sample code, the button is passed to the function. Then, the button's CSS style property "visibility" is changed to hidden. This hides the button from the user, so it is not visible on your web page.
-
1
References
- Photo Credit colors image by Dwight Davis from Fotolia.com