PHP Ferrari
PHP Ferrari

Reputation: 15664

Javascript add new class in body tag

If OS is MAC I set a variable & then on condition I want to add new class in body tag. Here is my code

<script type="text/javascript" language="javascript">
var mac=0;
    if(navigator.userAgent.indexOf('Mac') > 0){
        mac=1;
    }else{
        mac=0;
    }

if(1==mac){
    //document.body.className+='mac-os';
    //document.getElementsByTagName('body')[0].className+='mac-os';
    $('body').addClass('mac-os');
}else{
    //document.body.className+='win-os';
    //document.getElementsByTagName('body').className+='win-os';
    //$('body').addClass('mac-os');
    //$("body.className").addClass('win-os');
    //document.body.className += " " + 'win-os';
    $("body").addClass('win-os');
}
</script>

I have tried all but fail.

Upvotes: 1

Views: 6985

Answers (5)

7stud
7stud

Reputation: 48649

The html elements don't exist until after the page loads, but your js is executing before the <body> tag is even read by the browser. Your script tags come before the <body> tag, so the browser executes the js code first. If you need to delay execution of your js code until after the page loads(as is the case with most js code)--and you don't want to use jquery--then you can do this:

<script type="text/javascript">

window.onload = function() {

   //js code here

}

</script>

That function will not execute until the onload event occurs, which is after the page loads. The problem with the onload event is that all the images must load completely before the event fires, and that can take a long time, which will delay rendering any styles set by the js, or allowing buttons to fire onclick handlers set by the js.

As an alternative, you can put your script tags just before the closing body tag: ...

<script type="text/javascript">

  //js code here

</script>

</body>

In that case, all the html on the page will have been parsed by the browser when the javascript tags are encountered, and as a result all the html elements will exist. <img> tags that are parsed will exist, but the browser doesn't wait for them to load--the browser continues on and parses the rest of the html while the images are loading. Even the body element exists even though its closing tag hasn't been seen yet.

Better still is to link to a js file, so that your js code isn't cluttering up the html:

<script type="text/javascript" src="myjs.js"></script>
</body>

Also, if you have this:

<body class="bgcolor">

...and your js code does this:

document.getElementsByTagName('body')[0].className += 'mac-os';

...then you will get his:

<body class="bgcolormac-os">

...which is not what you want. You need to add a space in there:

     ....    += ' mac-os';

...so that you get:

<body class="bgcolor mac-os">

A comment on your code style: you need to add more spaces, for instance:

if (1 == mac) {
  document.getElementsByTagName('body')[0].className += 'mac-os';
}
else {
  document.getElementsByTagName('body')[0].className += 'win-os';
}

Also, don't use 'cuddled' else clauses--they are really ugly. Consider using the style in the example where the else starts on a new line. Code clarity is what you are aiming for--not the fewest number of bytes. You might also consider indenting just 2 spaces--js statements can get pretty long, so conserving space there can be helpful.

And to avoid having to re-type those long document.get.... statements and make your code easier to read, you can do thing things like this:

   var mybody = document.getElementsByTagName('body')[0];

   if (1 == mac) {
      mybody.className += ' mac-os';
    }
    else {
      mybody.className += ' win-os';
    }

Upvotes: 1

Amin Saqi
Amin Saqi

Reputation: 18977

Just put your jquery codes in $(document).ready(...) block to be sured that they execute in correct time...:

$(document).ready(function() {
    // jquery codes...
    $(document.body).addClass('your-class');
    // ...
});

Upvotes: 0

Alnitak
Alnitak

Reputation: 340055

It's likely that the body element simply doesn't exist at the point your current code is being executed.

Ensure that your code is not executed until the DOM is ready, by putting it inside a ready handler:

$(document).ready(function() {
    // your code
    ...
});

It would also work if you put it inside the <body> element, typically at the end of the page.

Upvotes: 4

ilyes kooli
ilyes kooli

Reputation: 12053

Your code works, maybe you forgot to wrap your code with

$(function () {
  //your code
}); 

?

$(function () {
    var mac = 0;
    if (navigator.userAgent.indexOf('Mac') > 0) {
        mac = 1;
    } else {
        mac = 0;
    }

    if (1 == mac) {
        //document.body.className+='mac-os';
        //document.getElementsByTagName('body')[0].className+='mac-os';
        $('body').addClass('mac-os');
    } else {
        //document.body.className+='win-os';
        //document.getElementsByTagName('body').className+='win-os';
        //$('body').addClass('mac-os');
        //$("body.className").addClass('win-os');
        //document.body.className += " " + 'win-os';
        $("body").addClass('win-os');
    }
});

Upvotes: 0

frogatto
frogatto

Reputation: 29287

If your script is in head your should wait until the body to be loaded, Change your code to:

$(document).ready(function(){
var mac=0;
    if(navigator.userAgent.indexOf('Mac') > 0){
        mac=1;
    }else{
        mac=0;
    }

if(1==mac){
    //document.body.className+='mac-os';
    //document.getElementsByTagName('body')[0].className+='mac-os';
    $('body').addClass('mac-os');
}else{
    //document.body.className+='win-os';
    //document.getElementsByTagName('body').className+='win-os';
    //$('body').addClass('mac-os');
    //$("body.className").addClass('win-os');
    //document.body.className += " " + 'win-os';
    $("body").addClass('win-os');
}
});

Or put your script into body tag:

<body>
<!-- your script -->
<!-- others -->
</body>

Upvotes: 2

Related Questions