last post we touched on how to select HTML elements using pseudo selectors. We looked into how we can use some of CSS pseudos to our advantage and when would you need to use this technique to manipulate your web pages. This post will be short and everything will be based on one example. We are now going to dive deeper in selecting our HTML elements using our CSS classes. We'll also extend on this by adding, and removing CSS classes dynamically, so without wasting any time lets get straight to it.
We will be making a traffic light for today. Yey! Should be fun right? Every 5 seconds we will be changing a background color of a div element by toggling between 3 CSS classes (Namely .green for go, .yellow for slow, and .red for stop). Sounds simple enough right? YES it is that simple. A basic implementation would be to check what kind of light we are currently at every 5 second interval and then change the CSS class. Now remember we will be using CSS classes to select our HTML elements. We will be starting from green to red and all the way back again The following does it all
setInterval( ) to simulate a countdown. This function accepts two parameters, first being the function to execute and second being the interval in milliseconds. In this function is where we toggle the CSS classes by checking the value of currentLight and determining the new light through if statements. Next are the two lines that do the switching of the CSS classes. The
removeClass( ) method removes a class from an HTML element and
addClass( ) adds a class. We therefore update the
currentLight variable after changing the light.
When selecting elements using CSS classes, a dot precedes the class name just like how you define them in your stylesheet. This is why we concatenate the the dot on the line:
$('.' + currentLight).removeClass(currentLight);
In this tutorial we further discussed using CSS classes in selecting and manipulating our HTML elements. There is one more post on this basics series which will touch-base on generating HTML elements and changing content dynamically. On future posts we will start doing more complex things with jQuery, looking at widgets, and rolling your own plugins