How to set CSS3 properties using JavaScript?

CSS3 & JavaScript

CSS3 & JavaScript

 

Overview: In this article I will talk about Cascading Style Sheet Version 3.0 and how to use it in JavaScript. Cascading style sheet is a style language used to define the presentation semantics of a document written in a markup language e.g. HTML, XHTML, XML, and SVG & XUL. Cascading Style Sheet primarily separates the document content from its presentation. This provides a better control while maintaining the document and also an easy access to modify the presentation of the document.

Introduction:

CSS3 is the latest version of Cascading Style Sheet which has separate modules for several documents. Each of these modules adds some or the other features. Some of the important modules added in CSS3 are:

  • Selectors
  • Box model
  • Backgrounds & Borders
  • Image values & replaced contents
  • Text effects
  • 2D/3D transformations
  • Animations
  • Multiple column layout
  • User Interface

CSS3 properties: 

The most commonly used properties of CSS3 are listed as under:

  • border-radius: border-radius is the most popular CSS3 property amongst all. Using this we can create circles.

Listing 1: Code to create a circle

[Code]

-webkit-border-radius: 4px;

-moz-border-radius: 4px;

border-radius: 4px;

[/Code]

  • box-shadow: box-shadow allows us to apply depth to our elements. box-shadow accepts four parameters :
    • x-offset
    • y-offset
    • blur
    • color of shadow
  • text-shadow: Similar to box-shadow this is also applied on text and accepts the same four parameters.
  • Multiple backgrounds: In CSS3 the background property is overhauled by multiple backgrounds. The following code snippet shows how to implement multiple backgrounds.

Listing 2: Code to have multiple backgrounds

[Code]

.box {

background: url(image/path.jpg) 0 0 no-repeat,

url(image2/path.jpg) 100% 0 no-repeat;

}

[/Code]

  • background-size: This property allows us to put the background image in a fixed size. This property accepts two parameters :
    • xwidth &
    • ywidth

Setting up CSS3 Properties:

Setting the CSS property via JavaScript is quite simple. We should first access the “style” object of an element, and then follow it up with the desired CSS property name to set it. If the CSS property name is hyphenated, such as “background-color”, the hyphen should be dropped and the character following it should be capitalized while referring to it in JavaScript. This is quite straight forward. With setting CSS3 properties, technically nothing changes; the problem knows which property to set! You see, as browsers raced to support CSS3 properties before they’re finalized, the use of vendor prefixes was what the browsers turned to offer an “interim” solution while the details of the official properties are hashed out. All major browsers have their own vendor prefix, which are:

Prefix Description
-ms- Microsoft CSS prefixes, such as -ms-filter, -ms-behavior, and -ms-zoom.
-moz- Mozilla CSS prefixes, such as -moz-box-shadow, -moz-border-radius, and -moz-transform.
-o- Opera CSS prefixes, such as -o-transition, -o-text-overflow, -o-transform.
-webkit- Webkit CSS prefixes (Safari, Chome etc), such as -webkit-box-shadow, -webkit-border-radius, and -webkit-transform.
-khtml- Konqueror CSS prefixes,such as -khtml-user-select and -khtml-border-radius

Table 1: CSS vendor prefix and their extensions

Setting up the CSS vendor properties in CSS is simply an exercise in patience, but when it comes to JavaScript, we can add logistics to it at the same time. While the normal rules of setting CSS using JavaScript still apply for setting vendor specific CSS properties, how do we know which property to set? For example, in Firefox 3.5, -moz-box-shadow is the supported property, while in IE9, it’s the official box-shadow property that is recognized. Surely we can just set all of the possible properties. A more efficient, elegant way is to probe the browser to see which CSS property it supports, then set that property only.

So how exactly can we go about setting a CSS3 property when different browsers may support a different variation of the property? The key lies in the fact that if a browser supports a particular CSS property, it will return a string value (empty string if not set yet) when you request it from an element on the page. In other words, the property exists on the element. If it doesn’t, the value undefined is returned instead. With that in mind, we can perform a one-time check before setting a CSS3 property which variant of the property it supports, and always turn to that one in our code. With that said, lets construct a function that accepts an array of CSS properties and returns the one the browser supports as a string:

Listing 3: Sample code to get the supported property

[Code]

function getsupportedprop(proparray){

var root=document.documentElement //reference root element of document

for (var i=0; i<proparray.length; i++){ //loop through possible properties

if (proparray[i] in root.style){ //if property exists on element (value will be string, empty string if not set)

return proparray[i] //return that string

}

}

}

//SAMPLE USAGE

var boxshadowprop=getsupportedprop([‘boxShadow’, ‘MozBoxShadow’, ‘WebkitBoxShadow’]) //get appropriate CSS3 box-shadow property

document.getElementById(“mydiv”).style[boxshadowprop]=”5px 5px 1px #818181″ //set CSS shadow for “mydiv”

[/Code]

The following code snippet uses the getsupportedprop() function to check which CSS box-shadow property is supported by the browser – “boxShadow”, “MozBoxShadow”, or “WebKitBoxShadow” when the button is clicked on:

Listing 4: Code snippet using the getsupportedprop()

[Code]

function alertboxshadow(){   alert(getsupportedprop([‘boxShadow’, ‘MozBoxShadow’, ‘WebkitBoxShadow’]))}

[/Code]

Using the above function, we can now go about setting CSS3 properties in JavaScript more easily, by passing into the function a list of possible variants of a particular CSS3 property, and letting the function figure out which one the browser supports and should be adopted. To drive this point home, let’s set up a demo where 3 different CSS3 properties can be dynamically added or removed to a link button with relative ease, thanks to the aforementioned function:

Listing 5: Final Code snippet

[Code]

<script>var shadowprop=getsupportedprop([‘boxShadow’, ‘MozBoxShadow’, ‘WebkitBoxShadow’])var roundborderprop=getsupportedprop([‘borderRadius’, ‘MozBorderRadius’, ‘WebkitBorderRadius’])var csstransform=getsupportedprop([‘transform’, ‘MozTransform’, ‘WebkitTransform’, ‘msTransform’, ‘OTransform’]) function changecssproperty(target, prop, value, action){                    if (typeof prop!=”undefined”)                                         target.style[prop]=(action==”remove”)? “” : value}</script> <body> <a id=”cfbutton” href=”http://www.codingforums.com”>Coding Forums</a> <script>var z=document.getElementById(“cfbutton”)</script> <a href=”javascript:changecssproperty(z, shadowprop, ‘6px 6px 8px rgba(0,0,0,.5)’)”>Add Shadow</a> <a href=”javascript:changecssproperty(z, shadowprop, ”, ‘remove’)”>Remove Shadow</a> <a href=”javascript:changecssproperty(z, roundborderprop, ’15px’)”>Add Round Border</a> <a href=”javascript:changecssproperty(z, roundborderprop, ”, ‘remove’)”>Remove Round Border</a> <a href=”javascript:changecssproperty(z, csstransform, ‘rotate(25deg)’)”>Add Transform Rotate</a> <a href=”javascript:changecssproperty(z, csstransform, ”, ‘remove’)”>Remove Transform</a>

[/Code]

Conclusion: So far we have seen that CSS is an integral part of any website/portal design. The style sheet gives the look and feel of any website and it makes the first impression. Learning the CSS3 properly helps us to understand the technical details and implement it successfully. To conclude our discussion, I must mention that although CSS3 is an accessory to website design but it must be learnt carefully to create the first impression. Hope you have enjoyed the article. Keep reading.

Tagged on: ,
============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share