manipulating CSS with JavaScript

 David
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.

// 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
Go Back to List Page

Leave a comment

Name : Comment : view emoticons
Please consider signing up for our website.
If you sign up and log in:
  •   You can avoid the "I'm not a robot" captcha when commenting
  •   You can also avoid typing your name every time
  •   You can upload a picture for each comment
  •   You can change or delete your comment within 1 hour
  •   You can track all the comments you posted on this site
  •   You can read blog posts that are only open to members
  •   You can look up blogs using the search feature
  •   More privileges for our friends & families coming...

OK, Sign me up!

Emoticons are a great way to visually express how you feel.
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.