Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing body tag style through JavaScript

I'm trying to write a script to change the width of the page, considering user's client width. It's something like this:

function adjustWidth() { 
    width = 0;
    if (window.innerHeight) {
        width = window.innerWidth;
    } else if (document.documentElement && document.documentElement.clientHeight) {
        width = document.documentElement.clientWidth;
    } else if (document.body) {
        width = document.body.clientWidth;
    }
    if (width < 1152) {
        document.getElementsByTagName("body").style.width="950px";
    }
    if (width >= 1152) {
        document.getElementsByTagName("body").style.width="1075px";
    }
}
window.onresize = function() {
    adjustWidth();
};
window.onload = function() {
    adjustWidth();
};

With this script I get an error from Firebug:

document.getElementsByTagName("body").style is undefined

Now my question is, how can i access the style of body? Because in the css sheet its selector and width property are defined.

like image 737
Nojan Avatar asked Jul 30 '12 12:07

Nojan


People also ask

Can JavaScript change HTML styles?

The HTML DOM allows JavaScript to change the style of HTML elements.

Can we add style using JavaScript?

And you want to add styles to this element. By using the JavaScript DOM methods, you can add the inline styles or global styles to the element.

Can we write JavaScript in body tag?

JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside both head and body.


2 Answers

That function returns a list of nodes, even though there's only one <body>.

document.getElementsByTagName("body")[0].style = ...

Now, that said, you may want to look into doing this with CSS instead of JavaScript. With CSS media queries, you make such adjustments:

@media screen and (max-width: 1151px) {
  body { width: 950px; }
}
@media screen and (min-width: 1152px) {
  body { width: 1075px; }
}

Media queries work in IE9 and pretty much all other modern browsers. For IE8 you can fall back to JavaScript or just let the body be 100% of the viewport width or something.

like image 138
Pointy Avatar answered Oct 12 '22 23:10

Pointy


document.getElementsByTagName('body')[0].style = 'your code';

Example:

document.getElementsByTagName('body')[0].style = 'margin-top: -70px';
like image 22
Naing Min Khant Avatar answered Oct 13 '22 00:10

Naing Min Khant