How do I use the jQuery.css() Method?

jQuery

Angular logo - cssThe jQuery CSS method allows you to style one or more DOM elements

Let’s begin with the HTMLElement.style property, which provides the access you need to style any DOM element. As a front-end web developer, you should make it a point to be familiar with this low-level DOM API. But the HTMLElement.style property comes with challenges, the two biggest being:

  1. The syntax is verbose, which leads to repetitive, boilerplate code.
  2. You cannot overwrite the HTMLElement.style property, which means that you cannot arbitrarily assign an object to it.

Now while it may seem like a minor detail that you cannot overwrite the HTMLElement.style property, this limitation does negate the ability to assign a well-crafted object to an HTMLElement’s style property. It also severely minimizes code re-use.

But the jQuery CSS method provides a powerful way to sidestep the quirky limitations of the HTMLElement.style property. It offers the ability to style DOM elements in a way that is considerably more elegant and expressive.

For one thing, the syntax is based on method chaining; you chain the css() method to the result of any jQuery query. So whether your query returns one or many elements, the style property and value that you pass to the css() method will be applied to the element(s) returned by your query. And in addition to a more concise syntax, there is the potential for code reuse. And finally, something that is often overlooked about this method: you are styling the DOM element directly (as opposed to using an external style sheet). As a result, the styles you apply will enjoy a high specificity.

In its most basic form, the jQuery.css() method takes two arguments. Both arguments are strings. The first argument is the name of the CSS property that you want to change. The second property is the new value for that CSS property. When you execute the CSS method against one or more DOM elements, jQuery adds a style attribute to each DOM element. And then, jQuery uses the second argument you provided as the value for that CSS property.

Try it yourself !

In the above example, there are five paragraph elements. Click each paragraph. When you do, you’ll see that each clicked element turns red. Click the JavaScript tab. In the JavaScript code, you’ll see that there is a click-event handler set up for each paragraph element. As a result, when any paragraph is clicked, jQuery executes the CSS method against that paragraph. Two arguments are passed to the CSS method. The first argument is color, which is the CSS property that we want to change. The second argument is red, which is the new value for that CSS property.

So, the approach taken so far is a very simple implementation of the css() method. In this case, we are passing only two strings. These two strings act as key/value pairs for the specified style property. But it is also possible to pass an object to the css() method. Significantly, this approach allows you to style multiple properties of an HTMLElement. This, of course, is an advanced implementation of the css() method, which I’ll cover in another article; for now, it’s just good to be aware of it.

Summary

So once you’ve had a chance to work with the css() method a little, I think you’ll agree that it is arguably one of the most genius features of jQuery. It frees you from two limitations of the HTMLElement.style property, and in addition to the elegant syntax, this method provides a way to re-use well-crafted code, in order to style multiple DOM elements. And if you look into the advanced syntax, you’ll see that multiple styles can also be applied within one call to the css() method.

Getting Started With CSS3 Transitions – Part III: Using Cubic-Bezier for More Lifelike Motion

CSS3

CSS3 LogoIn parts I and part II of this series Getting Started With CSS3 Transitions Part I and Getting Started With CSS3 Transitions Part II, we covered the absolute basics of CSS3 transitions. In those articles, we focused on applying transitions to single and multiple properties, and setting delays. In this article, we will review a more complex animation. The example is still pretty basic, but it is the next step with CSS3 transitions. We will discuss how varying the values of different properties can allow for animations that have a more lifelike quality.

IMPORTANT NOTE: In Part I of this series, we used all vendor prefixes needed to ensure cross-browser functionality. Here, for the sake of brevity, we will only include the -webkit- prefix. Please view these examples with a WebKit Browser, or edit the JSFiddle links as needed with -o- and -moz- prefixes.

Here is the markup we’ll need for our example:

Example # 1

In Example # 1, the first four rules are minified for brevity; there’s not too much to see there and it’s not really part of this discussion. It just sets the CSS for the elements in the page.

Notice that for the .foo class, we have specified “-webkit-transition-property”. This allows us to then set the duration and delay for each one of those properties. The end result is that when you mouse-over span.foo, it first grows in height, then it slides down, and then it changes color. We have configured it to behave exactly this way by setting the duration and delay separately for each one of the properties that changes.

When you mouse-over span.bar, things are a bit different. The first difference is that we use the CSS3 transition shorthand syntax so that all properties that can be transitioned are, and they share the duration and easing values. The second difference is that instead of using a named easing such as “linear” or “ease-in”, we use cubic-bezier, and specify the values needed for the required behavior. A deep discussion of cubic-bezier is out of the scope of this article, but at the bottom of this page are a few links that provide more helpful information on that topic.

When you look at the working example (JS Fiddle link), you will see that the behavior of span.foo and span.bar are quite different. Not only does span.foo differ because the properties that transition do so with different durations and delays, but span.bar really “feels” different because we used cubic-bezier to craft a much more real-world type of motion.

Here is the JS Fiddle link for Example # 1: http://jsfiddle.net/tQxxK/

Summary

In this article we learned how to create more complex animations using CSS3 transitions.We discussed how varying the duration and delay of multiple properties can create more life-like motion, and had a brief introduction to the cubic-bezier class.

 

We discussed how varying the duration and delay of multiple properties can create more life-like motion, and had a brief introduction to the cubic-bezier class.

Helpful Links for the CSS cubic-bezier class

http://www.azarask.in/blog/post/animation-css-transitions-jquery-easy/

http://www.the-art-of-web.com/css/timing-function/#.UTtpadE6WyM

https://developer.mozilla.org/en-US/docs/CSS/timing-function

http://roblaplaca.com/blog/2011/03/11/understanding-css-cubic-bezier/

http://www.roblaplaca.com/examples/bezierBuilder/

http://cubic-bezier.com/#.17,.67,.83,.67

Getting Started With CSS3 Transitions – Part II

CSS3

CSS3 LogoIn the previous article: Getting Started With CSS Transitions – Part I, we covered the very basics of CSS3 transitions. We covered how to apply a transition to the height property of an element, and how to add a duration in order to see the effect of our transition. We also discussed easing, which makes the transition feel more natural.

In this article, we will talk about applying transitions to all of the properties of the declaration that show a change in value, and setting a delay.

IMPORTANT NOTE: In Part I of this series, we used all vendor prefixes needed to ensure cross-browser functionality. For brevity sake, we will only include the -webkit- prefix. Please view these examples with a WebKit Browser, or edit the JSFiddle links as needed with -o- and -moz- prefixes.

Here is the markup we’ll need for all three examples:

Applying CSS3 transitions to all properties of your declaration

Example # 1A

In Example # 1A, we specify “-webkit-transition-property” and provide the value of “height”. So, even though the background color value changes on hover, the transition is only applied to height.

Here is the JS Fiddle link for Example # 1A: http://jsfiddle.net/eQd3n/

Example # 1B

In Example # 1B, we specify “-webkit-transition-property” and use the value: “all”. This means that ALL properties whose value changes on hover have the transition behavior applied (as long as they can be transitioned).

Here is the JS Fiddle link for Example # 1B: http://jsfiddle.net/DVFmd/

Example # 1C

In Example # 1C, we simply leave out “-webkit-transition-property”. By doing this, we achieve the exact same result as Example # 1B: For ALL properties whose values change on hover, the transition behavior is applied (as long as they can be transitioned).

Here is the JS Fiddle link for Example # 1C: http://jsfiddle.net/Hqv3J/

Example # 2

In Example # 2, we achieve the exact same result as Example # 1C, except we accomplish this by using the CSS3 transition shorthand notation, and provide “all” as the first value.

Here is the JS Fiddle link for Example # 2: http://jsfiddle.net/SKzAE/

Applying a delay to your CSS3 transition

Example # 3

In Example # 3, we have provided a fourth value to the CSS3 transition shorthand notation: a delay time. In this example, a value of “0.5s” is used, which forces the transition to wait a half-second before starting.

Here is the JS Fiddle link for Example # 3: http://jsfiddle.net/fsGLL/

Summary

In this article we learned three ways to apply CSS3 transitions to all properties in a declaration that see a change in value (as long as they can be transitioned). We also discussed CSS3 transition shorthand notation, and how to apply a delay to the effect.

Helpful Links for applying CSS3 transitions to multiple properties

http://www.w3.org/TR/css3-transitions/#animatable-properties

http://perishablepress.com/top-5-css-shorthand-properties/#transitions

http://stackoverflow.com/questions/9670075/css-transition-shorthand-with-multiple-properties

Getting Started With CSS3 Transitions – Part I

CSS3

JavaScript LogoThere’s lots to talk about when it comes to cascading style sheets and animation, but for this article, we’ll keep it short and sweet; just the basics you need for getting started with CSS3 transitions.

For the majority of the time we’ve been consuming HTML, making things move on web pages has been handled by JavaScript. At first it was a nightmare. jQuery has nicely abstracted away much of the cross-browser misery for us and I thank them dearly for this. Now, CSS3 provides functionality for animation that allows you to write less JavaScript, and leverage the brilliance of cascading style sheets, to handle your simple (and sometimes not so simple) animation effects.

Here is the markup we’ll need for all three examples:

Put your mouse over me

A Basic Transition

Example # 1

In Example # 1, we have the most basic CSS3 transition possible. On hover, we simply tell the browser to transform the height property from 100px to 300px. The only problem here is that the end result feels very CSS 2.1. Because the change is instant, we don’t really feel the transition effect. In order to do so, we need to specify a duration.

You may have noticed that we are using vendor prefixes. This allows us to make sure that our CSS code will work across browsers. I won’t get into a discussion about vendor prefixes here, but here is a good article about that topic:

http://css-tricks.com/how-to-deal-with-vendor-prefixes/

Here is the JSFiddle link for Example # 1: http://jsfiddle.net/w76ZL/

Specifying the Duration for Your CSS3 Transition

Example # 2

In Example # 2, we have specified a duration of two seconds to our CSS3 transition. This makes a big difference because in the first example, although we had applied a CSS3 transition, the lack of a duration property negated the transition effect. Now that we have added a duration property, the transition effect is much more evident.

Here is the JSFiddle link for Example # 2: http://jsfiddle.net/eAEpC/

Adding Easing to Your CSS Transition

Example # 3

In Example # 3, we added an easing value to our CSS3 transition. Easing is used to make the transition feel more realistic. Some common values are “ease-in”, “ease-out” and “linear”, but there are others.

Here is the JSFiddle link for Example # 3: http://jsfiddle.net/4tcLx/

Summary

In this article we discussed the very basics of CSS3 transitions. We covered how to apply a transition to the height property of an element, and we added a duration so that we can see the effect of our transition. We also discussed easing, which makes the transition feel more natural.

Helpful Links for CSS3 Transitions Basics

http://www.w3.org/TR/css3-transitions/

http://net.tutsplus.com/tutorials/html-css-techniques/css-fundametals-css-3-transitions/

http://www.css3.info/preview/css3-transitions/

http://blogs.msdn.com/b/eternalcoding/archive/2011/11/01/css3-transitions.aspx

Less CSS – The Absolute Basics

Less CSS

Less CSSLess CSS makes organizing, writing and managing your CSS code a breeze.

Although the CSS 1 specification was completed in 1996, it was not until 2000 that most major browsers fully implemented it. Ever since, we have all come to know and appreciate cascading style sheets. CSS rocks.

But…

The kind of logic that even the most basic programming languages enjoy is still absent from CSS. Granted, CSS is not a programming language, but with the kinds of challenges that today’s web developers face, concepts such as variables, functions and nested logic are difficult to live without in CSS. The end result is a syntax that quickly yields to unnecessary repetition and does not, by nature, allow you to mirror the very DOM you are styling. In addition, your CSS code base can quickly become large and difficult to manage.

Enter Less CSS.

This CSS preprocessor brilliantly allows you to employ the kind of structure and logic found in virtually any programming language. The syntax is easy to understand, it mimics your DOM structure and it allows you to keep your code base clean.

Two Implementation Methods

There are two ways that you can implement Less CSS: client-side or compiled. For the sake of simplicity, we will look at the client-side implementation and cover the compiled approach in a later post. Client-side implementation of Less CSS is not recommended for a large code base. In theory, it is inefficient and can quickly slow your page down. But it is perfect for getting to know Less CSS and for simple testing.

Client-side implementation is achieved in two steps. First, rename your .css file to .less. Also, in the LINK tag, change the “rel” attribute from “stylesheet” to “stylesheet/less”. Second, after your LINK tag that points to your .less file, pull in less.js via a SCRIPT tag. That’s it. Brilliant.

Example # 1

Example # 1 starts out by illustrating one very important point: Less CSS is a superset of CSS. This means that any valid CSS will work just fine in a .less file. In fact, there is no reason why you would not write normal CSS in a .less file. There are certainly situations where it makes perfect sense. For example, if I want all H1 and DIV tags to be 800px wide and have a top/bottom margin of 25px, then it just makes sense to say h1,div{ width:800px; margin:25px auto; }.

Nothin’ wrong with that!

The power of Less CSS really becomes apparent when you have a rule that forks. Once you start to write rules like this in CSS, things become inefficient:

Here we have referred to the “foo” class twice. Example # 1 illustrates how, by nesting our rules, we can refer to .foo only once, but define not only the style of the class, but any H2 elements that are descendants of that class. The same goes for the “bar” class.

Here is a link to a fully-functioning page from Example # 1:

http://sub1.kevinchisholm.com/blog/examples/less-css-example-1.html

Example # 2

In Example # 2, we see the use of the ampersand (“&”). This character is used to indicate the following kind of relationships:

  • div.className
  • p#idName
  • a:hover
  • ul:nth-child()
  • etc…

What’s happening here is that when we don’t use the ampersand, then the nested rule indicates a descendant. So, “div .foo” means “any element with the class foo that is a descendant of any DIV element.” But what if we want to indicate “any DIV element with the foo class?” Then we use the ampersand:

Here is a link to a fully-functioning page from Example # 2:

http://sub1.kevinchisholm.com/blog/examples/less-css-example-2.html

Example # 3

In Example # 3, we introduce two new concepts: variables and mixins.

Less CSS Variables

Variables in Less CSS are indicated by preceding the variable name with the “at” symbol (otherwise known as an ampersat). You then initialize that variable as if you were writing a CSS rule. It is important to note that in Less CSS, variable values cannot change during the life of the page; once you define a variable, the value you have assigned it remains fixed.

Less CSS Mixins

I like to think of Less CSS Mixins as functions. In my opinion, the syntax is similar to a JavaScript function:

In the above Less CSS mixin, the arguments are optional. If you include an argument, you must initialize it. But, you do not have to use the argument inside of the mixin, nor do you have to pass-in the argument when calling the mixin. The mixin simply does whatever you tell it to do (i.e. it returns whatever CSS you define inside of it). The power of the mixin is that you can pass it a value as an argument, and this will override the initialized value.

You’ll also notice the last line inside of the mixin: “//etc…”. This is a Less CSS comment. While you can always use valid CSS comment syntax /* comment */ you can also use the double-slash syntax that is found in JavaScript: “//comment”

Here is a link to a fully-functioning page from Example # 3:

http://sub1.kevinchisholm.com/blog/examples/less-css-example-3.html

Summary

In this article, we covered the absolute basics of Less CSS. We learned what Less CSS is and about simple client-side implementation. We also covered nested rules, variables and mixins. These are the very basics of Less CSS and there is much more to discover and talk about.

Helpful Links for Less CSS basics

http://lesscss.org/

http://en.wikipedia.org/wiki/LESS_(stylesheet_language)