Javascript: Dynamically Altering CSS Properties
I’ve been on a string of javascript posts, starting with Javascript: Opportunities Abound and then Javascript: Changing Class Names to Alter CSS. Well now I want to talk about a variant of altering CSS classes, and that is just altering inline style. I use this infinitely more than changing a CSS class. You can do a lot of very easy and simple interactions for the user that are really quite easy. You can show and hide divs, change background colors or images (I’ll use that to create textbox watermarks in my next post), and much more.
So either in an external Javascript file (which is called the same way as an external CSS file), or in the head of your HTML inside a <script> tag, include the following javascript:
The Javascript:
function changeInlineStyle(tagID){
var theTag = document.getElementById(tagID);
if (theTag.style.display == 'block')
theTag.style.display = 'none';
else
theTag.style.display = 'block';
}
The javascript first takes in a string with the tag ID that you send to it in the HTML below. Then, it creates an object that represents that ID which is named theTag. Then with a simple if statement, the javascript checks to see if the object is visible. If it is, it hides it, if it is hidden, it shows it. This is great for toggling a div with certain content. You can change different aspects of style though. Try "backgroundImage" or "backgroundColor" to change background characteristics. You can mess around with any aspect of tag’s style that you want. Text color, float, width, height, whatever you want. I have found the most common ones I use are display, backgroundColor, and backgroundImage though.
Here is the HTML that goes with the JS:
<a href="#" onclick="changeInlineStyle(targetTag);"> <div id="targetTag">This div will hide when the link above is clicked</div>
Yep, simple as that! When the link is clicked, it calls the javascript function, sending over the id to identify the tag it should work with. In this case, the link targets the div below it. Simple as that! I’ll talk about textbox watermarks next. Comments? Questions?