views:

31

answers:

3

Hello,

I know there are JavaScripts or jQuery plugins which set some body classes (e.g. something like that <body class="ff3.5 ff win gecko some-awesome-icons-article-with-100-icons">) I don't know how that is called...? Do you know what I mean and have you a link/name of it? The path to the article set as css-body-class is more important for me than for example the browser or OS.

A: 

If I've understood your query, you need to add a class to certain tag. Using jquery this is how it can be done.

$('body').addClass('anyClass');
philar
Thanks but I know how to set/add a class with jQuery ;-)! But that I don't need...
Poru
+1  A: 

I think you're asking for code that will extract the "filename" portion of the url path, and set that as a class name on the body element.

If so, then here's the basic idea:

$(document).ready(function() {

    var parts = window.location.pathname.split('/');

    var basename = "default-no-basename";
    if( parts && parts.length ) {
        var idx = parts.length-1;
        if( parts[idx] == '' && parts.length > 1 ) {
            --idx;
        }
        basename = parts[idx];
    }
    //alert("basename: "+basename);
    $(body).addClass( basename );
});

That code simply extracts the portion of the page url following the final slash, and writes it into the class attribute of the body tag. If the url path is a "directory" (ie. it ends with a slash), then it'll use the trailing directory name instead. If the url path is just '/', then it'll default to adding the classname 'default-no-basename'.

Important: The above code does not do anything to ensure that the classname is compliant with the allowed characters in css classnames. So if your url was something like: http://example.com/abc/my-cool-page(with stuff).html, then you're going to have problems, because the css class will be set to "my-cool-page(with stuff).html".

You would therefore want to either ensure that this is never being called on a page that has special chars (like (, ), ., and the [space] character in the above example). Or you'll want to add some checking in to that logic to strip out disallowed chars.

good luck.

Lee
A: 

I found a JavaScript solution: http://snipt.net/mountainash/javascript-adds-classes-to-body-based-on-url/

Poru