Setting a CSS value as a javascript variable - javascript

Ok, I want to have a CSS value such as the value of width: 50%; to be a variable defined in pixels. Let's say that the 50% width is perhaps 1000px, or 500px. I want the javascript to detect the pixel value of the percent.
I have tried several times with absolutely no luck.

You can do it like below using jquery.
var width = $('#your_id').width();
Example
var width = $('#myDiv').width();
alert(width + 'px');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width: 200px;">
<div id="myDiv" style="width: 50%;"></div>
</div>

var total_width = $( window ).width();
var display_width = 50; //50%
var my_width_px = ((display_width * total_width) / 100); // 100 = 100%
This will may be helpful for you.

You can get the width in pixels using jQuery
var width = $('#mydivid').width();
Set the width of a div using jQuery
$("#mydivid").css("width", your_new_width);
Get width using javascript
document.getElementById("mydivid").offsetWidth;

Related

HTML Resize Div with Javascript

I am working on an online presentation editor.
I have a div (which should be the slide - the format is 16x9)
If the user decides to export it as pdf, the div should resize to 1920x1080, and then it should be exported (so that the pdf is not the same size as the user window, but always 1920 x 10800. My problem is, that if I set the width in JS like this:
$('#content').css('min-width', `1920px`);
$('#content').css('min-height', `1080px`);
$('#content').css('width', `1920px`);
$('#content').css('height', `1080px`);
only the container resizes, but the content doesn't.
This is what the slide looks like in the app
This is what the exported pdf looks like because the content doesn't resize.
If you have any idea, please let me know.
HTML:
<div style="background-color: green" id="content">
<h1 style="color: black">Hallo Welt</h1>
<p>Hallo 3CHIF!</p>
</div>
Well, maybe there's other solutions (or even better solutions), but I tought about scale(), this will scale the div and consequently, it's contents.
So, how I did it:
I estipulated the desired width and height (in your case, 1920x1080), then I got the div current size.
Divided the desired sizes by current sizes to get the "ratio", then used the CSS transform to set the new scale(x, y), as you can see in the below example.
You can base yourself in the code to get your solution
var desiredWid = 1920;
var desiredHei = 1080;
var theDiv = $("#content");
var currentWid = theDiv.width();
var currentHei = theDiv.height();
var ratioW = desiredWid / currentWid;
var ratioH = desiredHei / currentHei;
theDiv.css("transform","scale(" + ratioW + "," + ratioH + ")")
var currentSizes = theDiv[0].getBoundingClientRect();
console.log("Adjusted Size:", currentSizes.width + " x " + currentSizes.height)
#content {
width: 2500px;
height: 1200px;
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content">Original Size: 2500x1200</div>
I used jQuery since I saw you are using, but you can do it with pure JS also.
try
#content{
width:100%;
height:100%;
}
if you want to have initiate max with or height you can add it to css too
then see if .css work or not
or must I say
then use js

change fontsize on resize inside a div with javascript

I am fairly new with javascript, but i'm trying to lurn.
I have an image with a div container over the image. The div container contains 2 inner div for a Title and some text. THe font size of the title is bigger than the text.
My screen innerwidth that I use to work and develop is 768.
I want to have the javascript change the fontsize on load and on resize based on proportion of the browser window... so if the browser window is 30% larger... the font should be 30% larger then defined in the css... This is the code I made.. but it's not working.
<head>
<style type="text/css">
#container{
position: absolute;
top:10%;
left: 10%;
background-color:#F30;
}
#boxtitle{
font-size:3em;
}
#boxtxt{
font-size:0.9em;
}
</style>
<script>
onresize=onload=function()
{
var innerW = window.innerWidth;
var boxtitle = document.getElementById("boxtitle").style.fontSize;
var boxtxt = document.getElementById("boxtxt").style.fontSize;
var ratio = innerW / 768;
boxtitle = boxtitle * ratio;
boxtxt = boxtxt * ratio;
}
</script>
</head>
<body>
<img src="main_pic3.jpg" width="100%" />
<div id="container">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td><div id="boxtitle">TITLE</div></td>
</tr>
<tr>
<td><div id="boxtxt">TXT</div></td>
</tr>
</table>
</div>
</body>
You are setting the value of your variables to the font sizes (you are not storing references to the DOM elements.) Also, try using parseInt to make sure you get any strings out of your numbers.
Try:
var innerW = parseInt(window.innerWidth),
boxtxt = parseInt(document.getElementById("boxtxt").style.fontSize),
ratio = innerW / 768;
document.getElementById("boxtxt").style.fontSize = (boxtxt * ratio) + 'px'; //etc.
One thing to note (I haven't tested it in other browsers) is that in Firefox for Mac, style.fontSize only returns a font-size that's inline to an element, and not the font-size on your stylesheet.
So, an option is this:
function getStyle(object,prop) {
if(getComputedStyle) {
return getComputedStyle(object)[prop];
} else if (object.currentStyle) {
return object.currentStyle[prop]; //IE
}
}
//implement it
getStyle(document.getElementById('someElement'),'fontSize'); //for example, outputs 12px
One thing I want to point out is that if you try to multiply an empty string by a number (for example, if you use style.fontSize where there are no inline styles and multiply that [which is now an empty string] by an integer, such as your screen width [which in this case is 768]), it will output 0, which would set your font-size to 0, thus making it disappear:
console.log(document.getElementById('download').style.fontSize * 768);
//outputs 0
Additionally, I noticed you are using resize along with your onload handler. I might suggest putting resize inside your onload handler instead, unless you know that you won't be putting other code inside your onload handler (because this would cause lots of stuff to happen every single time the window is resized.)
Another option for handling font size based on screen size are CSS media queries (I suggest a Google search for that.)
onresize=onload=function()
{
var innerW = window.innerWidth;
var boxtitle = document.getElementById("boxtitle").style.fontSize;
var boxtxt = document.getElementById("boxtxt").style.fontSize;
var ratio = innerW / 768;
boxtitle = boxtitle * ratio; //<--- try appending px example below up to you how you append it
document.getElementById("boxtitle").style.fontSize = '100px'
boxtxt = boxtxt * ratio; //<--- try appending px
}
first of all, you have to store original values, otherwise you will be getting different font sizes on every resize
then, you just have to append it
onresize=onload=function()
{
var ratio = window.innerWidth / 768;
document.getElementById("boxtitle").style.fontSize = 3*ratio + 'em';
document.getElementById("boxtxt").style.fontSize = 0.9*ratio + 'em';
}
another approach is to use viewport based metrics - http://snook.ca/archives/html_and_css/vm-vh-units
How about using percentage for font sizes instead so everything stay proportional also. You just have to bound top level with font size that is not in percentage like in the example. Otherwise, you will have a nightmare trying to maintain so many font sizes in Javascript.
Here's an example: http://jsfiddle.net/yL89q/
HTML:
<div id="container">
<h1>Title</h2>
<div class="description">Description</div>
</div>
CSS:
#container{
font-size: 13px;
}
.container h1{
font-size: 150%;
}
.container .description{
font-size: 100%;
}
JS:
onresize=onload=function(){
var innerW = window.innerWidth;
var ratio = innerW / 768;
var boxtitle = Math.round(13 * ratio);
document.getElementById("container").style.fontSize = boxtitle + 'px';
}

Setting width and height as a percentage in JavaScript

Here is my JavaScript code:
a.width = a.width ? a.width : 640;
a.height = a.height ? a.height : 360;
How can I make the 640px and 360px percentages instead? I want them both to be 70% of the windows size.
If the container of the element have sizing specified already, then you can simply use percentages in CSS. For instance:
.#my-el {
width: 70%;
height: 70%;
}
<div id="my-el"></div>
However, if you have to use JavaScript for some reason, you could do something like:
el.style.width = Math.round(document.documentElement.clientWidth * .70) + 'px';
You may have to use a more complex approach to determine the viewport size for cross-browser support however, but this question was already answered.
percentage is a relative value.
you need to have relative value like screenWidth (for suppose) 1240px so that you will get percentage of that value.
Example
var pixels = 100;
var screenWidth = window.screen.width;
var percentage = ( screenWidth - pixels ) / screenWidth ; // 0.92%
To set an element's width or height as a percentage, there are a couple of options available.
Firstly, you can set the element's dimensions as a percentage of its container like this:
element.width = "70%";
element.height = "70%";
Alternatively, you can set the dimensions as a percentage of the screen size instead like this:
element.width = "70vw";
element.height = "70vh";
These values stand for "viewport height" and "viewport width".
However, since both of these options use basic CSS values, it may be preferable to add a CSS class dynamically to the element instead of setting its style properties directly in JavaScript. For example:
element.classList.add("my-class");
Then, define the .my-class selector in a stylesheet like this:
.my-class {
width: 70%;
height: 70%;
}

jQuery calculate img's real height / width values which coming from server

I am in a situation that; need to calculate image's original width and heigth values when one of them defined 0 on css. I can't change CSS with jQuery, need to solve like this:
Here is example link.
CSS:
img { width:0px; }​
jQuery:
var imgHeight = $('img').height();
alert(imgHeight);//which returning 0 ofcourse
I hope this is possible with less code, thanks,
Try this:
var img = $("img")[0];
alert( img.naturalWidth + "x" + img.naturalHeight );
http://jsfiddle.net/mjaA3/50/
You could clone the element to a new hidden DOM node (I assume you want to hide it here). Then remove the CSS, then measure the dimensions.
var img = $('img'),
imgHeight = img.css("width","auto").height();
img.css("width","0");
alert(imgHeight);
Here is a fiddle. All we do is temporarily set the height to it's automatic value (which is the image's 100% width), grab the height, and reset the image to width:0;.
EDIT: Since you can't manipulate CSS directly, you can change the class:
var img = $('img'),
imgHeight = img.addClass("auto").height();
img.removeClass("auto");
alert(imgHeight);​
And the CSS:
img {width:0;}
img.auto {width:auto;}​

Modify mask height dynamically in javascript

I have to increase the height of .x-mask class through javascript(extjs). I will get dynamic height by using
var hgt = document.documentElement.scrollHeight;
Then I have to apply it instead of
.x-mask {
height: 100% !important;
}
through javascript dynamically.
Have you used ,
document.documentElement.style.height = '100%!important';
or
document.documentElement.style.height = document.documentElement.scrollHeight + 'px';
If you are using any element like div or span where you have assign this class like
<div id="mydiv" class="x-mask">
try this js
document.getElementById('mydiv').style.height=hgt;
And if you are using jQuery, then try
$('.x-mask').height(hgt);

Categories

Resources