Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript variable to css

I am working on a small html page. I am using javascript to get the dimensions of the screen. I need to pass that variable to a css style like below. How can I do this? Also I notice that I need to put the "px" at the end of the value, like top: 100px not top:100. How can I add that to my variable as well? Thanks for any help

<script type="text/javascript">
    var percent =1;
    var myWidth = Math.round( screen.width * percent);
    var myHeight = Math.round( screen.height * percent);
</script>

<style type="text/css">
    div.content {
margin: auto;
top: myHeight ;
width: myWidth ;
    }
</style>
like image 914
fghajhe Avatar asked May 11 '13 22:05

fghajhe


2 Answers

If you intend to use LESS CSS you can try out this :

    @percent: 1;
    @height: `Math.round( screen.height * @{percent})`;
    @width: `Math.round( screen.width * @{percent})`;
    div.content {
    margin: auto;
    top: @height;
    width: @width;
    }

If you intend to use JQUERY you can try out this :

var percent=1;
$("div.content").css('top', Math.round( screen.height * percent)+'px');
$("div.content").width(Math.round( screen.width * percent));

If you intend to use JS you can try out this :

var percent=1;
document.querySelector('div.content').style.top = Math.round( screen.height * percent)+'px';
document.querySelector('div.content').style.width = Math.round( screen.width * percent)+'px';
like image 152
Robin Rizvi Avatar answered Oct 18 '22 00:10

Robin Rizvi


With pure JS, you could get all div via getElementsByTagName, then filter for a content class name.

For newer browsers (most especially for IE):

  • You could also do getElementsByClassName, then filter all those that are divs.
  • You could use querySelectorAll which directly returns a list of matches.

Then for each that match, do:

currentDiv.style.top = myHeight;
currentDiv.style.width = myWidth;
like image 30
Joseph Avatar answered Oct 17 '22 23:10

Joseph