manipulating CSS with JavaScript
Sometimes, I need to change the CSS of an element using a JavaScript, typically when certain event is triggered by an user action.
This, however, is not so trivial and as always, I just google and look up the javascript example. Today, I realized why this is not so trivial and rather tricky.
One of the reasons is due to the fact that JavaScript does not allow hyphens in names and some CSS properties, such as background-color has hyphens. In this case, you can use "camelCase" (hence "background-Color" becomes "backgroundColor" when referenced in JavaScript).
Here's a really good example, which demonstrates the manipulation of CSS of element as well as the manipulation of other (non-style) element attributes.
This, however, is not so trivial and as always, I just google and look up the javascript example. Today, I realized why this is not so trivial and rather tricky.
One of the reasons is due to the fact that JavaScript does not allow hyphens in names and some CSS properties, such as background-color has hyphens. In this case, you can use "camelCase" (hence "background-Color" becomes "backgroundColor" when referenced in JavaScript).
Here's a really good example, which demonstrates the manipulation of CSS of element as well as the manipulation of other (non-style) element attributes.
// JavaScript demonstration
var square = document.getElementById("square"),
clickMe = document.getElementById('clickMe'); //Keeping it unobstrusive
function doDemo () {
var button = this;
square.style.backgroundColor = "#fa4";
button.setAttribute("disabled", "true");
setTimeout(clearDemo, 2000, button);
}
function clearDemo (button) {
var square = document.getElementById("square");
square.style.backgroundColor = "transparent";
button.removeAttribute("disabled");
}
clickMe.onclick = doDemo; //Onclick call. Pass no arguments
Here's working example in jsfiddle
Leave a comment
If you sign up and log in:
OK, Sign me up!
However, there are times when unintended content is converted to emoticon because the content happens to have one of the emoticon symbols. That's why it's always good idea to preview your comment before posting and when you see this type of problem, you can indicate NOT to auto convert.