Applying CSS using javascript

I am using mootools to create a javascript slideshow and everything works fine, however with javascript turned off it doesn’t degrade gracefully.

Therefore I need to apply the following CSS rules only when javascript is enabled.

.mask {
position: relative;
width: 760px;
height: 225px;
overflow: hidden;
}

#box {
position: absolute;
}

span img {
display: block;
border: none;
}

I’m a bit of a noob when it comes to javascript, can anyone help?

The simplest way if this should apply to just 1 element, is to applicate the class name via javascript by finding the element with it’s id:


var _elm=document.getElementById('id_of_the_element');
_elm.className="mask";
//now for the box id:
var _elm=document.getElementById('box');
_elm.style.position="absolute";

Or you could update every element of a certain type:


//to get every element of a certain type
var _aryElm=document.getElementsByTagName('li');  //return an array with every <li> of the page
for( x in _aryElm){
  _elm=_aryElm[x];
  _elm.style.backgroundColor="red";
  _elm.className="a_class";
}

The only thing to take care, is that the CSS attribute are converted to camel case.
The - is dropped, and the first letter of the next word is in upper case.
background-color is backgroundColor, margin-bottom is marginBottom and so on…

You have two options. You can either modify/add-to the actual CSS declatations or you can apply inline styles to the required elements.

If we look at your first rule. You want to apply four CSS declerations to all elements with a class of “mask”. The first step would be to find all those elements.

Now, since MooTools is modular and I don’t know if you’ve got the required modules, I’ll be showing you this in straight-up JavaScript (no libs):

Since the “getElementsByClassName” method is not supported by all browsers we need to make our own:


function getElementsByClassName(searchClass) {
    if(document.getElementsByClassName) {
        var els = document.getElementsByClassName(searchClass);
        return els;
    }
    var els = document.getElementsByTagName('*'),elsLen=els.length,classElements=[]; // Gather all nodes
    var pattern = new RegExp("\\\\b"+searchClass+"\\\\b"); // pattern to check for class presence
    for (var i = 0,j = 0; i < elsLen; i++) { // Loop through each node in document
        if ( pattern.test(els[i].className) ) { // test for above pattern
            classElements[j] = els[i]; // Transfer element reference to seperate array
            j++;
        }
    }
    return classElements; // return array full of elements which have searched class
}

This also checks for the native “document.getElementsByClassName” which will work in more modern browsers and it will fallback to a more cross-browser compatible method if this native method is not available.

So in order to gather all elements with a class of “mask” we would do this:


var maskElements = getElementsByClassName('mask');

Now we would need to loop though each of the elements and add the styles. First we should create a function which will add styles for us, this speeds up the whole process and avoids any repition - so we’ll have one single reliable method for adding styles:


function addStyles(element,styles) {
    for (var i in styles) {
        element.style[i] = styles[i];
    }
}

^ see, very simple! :slight_smile:

You could make this function more flexible (look here: http://enhance.qd-creative.co.uk/2008/08/02/three-useful-javascript-functions/) but for now this seems suitable…

Right, now we can loop through all the “mask” elements and apply the styles:


var maskElements = getElementsByClassName('mask');
for ( var i = 0; i < maskElements.length; i++ ) {
    addStyles(maskElements[i],{
        position: 'relative',
        width: '760px',
        height: '225px',
        overflow: 'hidden'
    });
}

Now, all elements with a class of “mask” will have the above styles applied.

Your second ruleset for #box is much simpler to apply since it’s just one element.


var box = document.getElementById('box');
addStyles(box,{
    position: 'absolute'
});

The “span img” ruleset is a bit more complicated. You’ll have to loop through all span elements and within each iteration, loop through all (if any) child elements whcih are images. So:


var spans = document.getElementsByTagName('span'), spansLength = spans.length;
while (spansLength--) {
    var imgs = spans[spansLength].getElementsByTagName('img'), imgsLength = imgs.length;
    if(imgsLength>0) {
        while (imgsLength--) {
            addStyles(imgs[imgsLength],{
                display: 'block',
                border: 'none'
            });
        }
    }
}

Please note that “while(spansLength–)” is basically the same as “for ( var i = 0; i < maskElements.length; i++ )” … it’s just a bit quicker…

I hope you’ve learnt something today. :slight_smile: