Pass a JavaScript variable to CSS

1

What I want is to catch the total height of the page and apply a CSS depending on the result.

JS:

$altura = document.body.scrollHeight;

CSS:

#id{
height: $altura;
}

Something like that, how should it be done?

    
asked by Lluís Puig Ferrer 08.09.2017 в 16:05
source

4 answers

2

The total height of the page in CSS is 100vh and the width is 100vw

Currently you can not pass variables from JS to CSS

Solution:

#id {
    height: 100vh;
}

Pd: The less you use the JS, the better for the WPO of your website

    
answered by 08.09.2017 / 16:08
source
1

You can apply css from Javascript. For example, using querySelector (it is also possible otherwise if of incompatibility, since querySelector is not compatible with old browsers [see specifications in the link]).

//Usamos parseInt para quitar las letras como px
var paginaAltura = parseInt(window.getComputedStyle(document.querySelector("body")).height);
console.log("Altura inicial body: " + paginaAltura);


var paginaAlturaNew = parseInt((paginaAltura + 100));
console.log("Nueva altura body: " + paginaAlturaNew);


document.querySelector('body').style.height = paginaAlturaNew + "px";

console.log("Altura final del body : " + window.getComputedStyle(document.querySelector("body")).height);

// Con un div

var divAltura = parseInt(window.getComputedStyle(document.querySelector("#test")).height);
console.log("Altura inicial div: " + divAltura);


var divAlturaNew = parseInt((divAltura + 100));
console.log("Nueva altura div: " + divAlturaNew);


document.querySelector('#test').style.height = divAlturaNew + "px";

console.log("Altura final del div : " + window.getComputedStyle(document.querySelector("#test")).height);
body {
  height: 100px;
}

#test {
  height: 10px;
}
<body>
  <div id="test">
    <p>Lorem ipsum dolor sit amet</p>
  </div>
</body>
    
answered by 08.09.2017 в 19:07
0

The way you propose it could not be done, but you can do it like this:

Top of the document :

document.getElementById("id").style.height = document.documentElement.scrollHeight+"px"

considering high body :

document.getElementById("id").style.height = document.body.scrollHeight+"px"
    
answered by 08.09.2017 в 17:27
0

You can use Jquery to make your life easier. link

Once loaded jquery you can use the sentence:

$(function(){ 
   var windowHeight = $(window).height(); 
   console.log(windowHeight)
});

with this you can modify the properties of the window at your whim, such as:

$(function(){
   $(document).css({ "background": "chartreuse" });
});
    
answered by 08.09.2017 в 18:13