Sunday, July 7, 2013

Accessing CSS from JavaScript

It many time brought back to me, that there are lot of times when you need to change the one of the CSS property of and element via JavaScript. Either to create animations or some cool effects. This is a simple blog post describing about the same.
In the new Windows8 application project, here is the code of the default.html file I have modified.

   1: <body id="pageBody">    
   2: </body>

We have given ID to the body tag so as to access it through JavaScript, using document.getElementByID. We can than change lot many styles of the body like this:

image

For now, we are going to set the background color. For that, we just set the backgroundColor property to #FF0000, i.e. RED.

   1: (function () {
   2:     "use strict";
   3:  
   4:     WinJS.Binding.optimizeBindingReferences = true;
   5:  
   6:     var app = WinJS.Application;
   7:     var activation = Windows.ApplicationModel.Activation;
   8:  
   9:     app.onactivated = function (args) {
  10:         if (args.detail.kind === activation.ActivationKind.launch) {
  11:             if (args.detail.previousExecutionState !== 
  12:                             activation.ApplicationExecutionState.terminated) {
  13:                 //Set the background color to RED
  14:                 document.getElementById('pageBody').style.backgroundColor = "#FF0000"
  15:             } else {
  16:                 // TODO: This application has been reactivated from suspension.
  17:                 // Restore application state here.
  18:             }
  19:             args.setPromise(WinJS.UI.processAll());
  20:         }
  21:     };
  22:  
  23:     app.oncheckpoint = function (args) {
  24:         // TODO: This application is about to be suspended. Save any state
  25:         // that needs to persist across suspensions here. You might use the
  26:         // WinJS.Application.sessionState object, which is automatically
  27:         // saved and restored across suspension. If you need to complete an
  28:         // asynchronous operation before your application is suspended, call
  29:         // args.setPromise().
  30:     };
  31:  
  32:     app.start();
  33: })();

This is how we can set the CSS property of any control in JavaScript.

Happy Reading.

Share this post

0 comments

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
© 2013 Neelesh Vishwakarma
Posts RSS Comments RSS
Back to top