I want to increase the height of the div tag on click of button. Every time a user clicks a button it should increase the height of that particular div tag, say by 200px or so..
HTML
<div id="controls">
<input type="button" onclick="incHeight()" id="btn" name="btn">
</div>
<div id="container" style="min-height:250px;"> </div>
The below script works properly
Javascript
<script type="text/javascript">
function incHeight()
{
document.getElementById("container").style.height = 250+'px';
}
</script>
But I want to do something like this, which is not working. The problem I think is the 'px' portion in the value. Anybody have any idea how to extract the INT portion of the value...
<script type="text/javascript">
function incHeight()
{
document.getElementById("container").style.height += 250;
}
</script>
The problem is how do I get the '250' portion of the height value neglecting the 'px' in javascript..
Try this:
function incHeight() {
var el = document.getElementById("container");
var height = el.offsetHeight;
var newHeight = height + 200;
el.style.height = newHeight + 'px';
}
Fiddle
Try something like
var container = document.getElementById('container');
container.style.height = (container.offsetHeight + 250) + "px";
In case offsetHeight is not working, try parsing the style.height for its numeric value instead.
var currentHeight = (container.style.height) ? (parseInt(container.style.height.match(/[0-9]+/)[0]) : container.offsetHeight;
Also, simply parseInt(container.style.height) might work
Try this:
getElementById('container').setAttribute("style","height:500px");
or
function resize(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
You can use a regular expression to only keep the numbers in the string:
var style = document.getElementById("container").style;
style.height = style.height.replace( /^\D+/g, '') + 'px';
Related
How can I change an element with a fixed width in px when i resize the window? I need to use an absolute unit, i can not use relative units like % or vw.Every time the window is resized with 1 px i need to decrease the element width by 0.2px.
I tried to use the window resize eventListener but i don't know what calculations needs to be done.
What you want can be achieved by using javascript. I've created a logic to do that :
<script>
function myFunction() {
var initialscreenwidth = window.innerWidth; //Set Initial Screen Width
setInterval(function() { //looping the script
var screenwidth = window.innerWidth;
var difference = initialscreenwidth - screenwidth; //Calculating the change in screen-size
if (difference != 0) { //Checking if there is a change in width
var element = document.getElementById('demo');
var style = window.getComputedStyle(element, null).getPropertyValue('font-size'); //Getting default font-size of the element
var initialfontsize = parseFloat(style);
var fontdifference = -(parseFloat(difference) / 5); //1px change in screen-size = 0.2px change in font-size
var newfontsize = initialfontsize + fontdifference;
var newfontsizepx = newfontsize + "px";
if (newfontsize > 1) {
document.getElementById("demo").style.fontSize = newfontsizepx;
}
}
initialscreenwidth = window.innerWidth;
}, 300); //reloads in every 300ms
}
myFunction();
</script>
Paste this at the end of your body section, somehow using this in the head section is not working.
I am trying to get the height and width of the browser window and display it on the body as well as changing the height to match.
Here's my current code:
window.onresize = window.onload = function() {
width = this.innerWidth;
height = this.innerHeight;
document.body.innerHTML = width + 'x' + height; // For demo purposes
}
The above code displays the width and height on the body ok, now time to add it to a css variable:
var header = document.querySelector('.header')
window.onresize = window.onload = function() {
width = this.innerWidth;
height = this.innerHeight;
header.style.setProperty('--height', height);
header.style.setProperty('--width', width);
document.body.innerHTML = width + 'x' + height; // For demo purposes
}
I know the code is not correct but I can't find any sample to compare with, here's a fiddle just in case the code is not enough.
https://jsfiddle.net/rbtwsxd8/6/
You have a number of different issues here:
(at least in the fiddle) you were trying to document.queryselect the header element before it existed
your debug code overwrote the header element by setting document.body
You omitted the units when setting the height and width (This used to work in "quirks mode" but will not work in modern doctypes.)
You added extra double hyphens when trying to set the height and width
Here's a working version which corrects these problems:
window.onresize = window.onload = function() {
var header = document.querySelector('.header');
// your original code used 'this.innerWidth' etc, which does work
// (because the function is being run on the window object) but can
// be confusing; may be better to refer to the window object
// explicitly:
var width = window.innerWidth;
var height = window.innerHeight;
header.style.width = width + "px"; // need 'px' units
header.style.height = height + "px";
// the above is equivalent shorthand for
// header.style.setProperty('height', window.innerHeight + 'px');
// header.style.setProperty('width', window.innerWidth + 'px');
// setting this inside the header, so we don't remove it in the process:
header.innerHTML = width + "x" + height;
}
https://jsfiddle.net/pm7rgx4q/1/
window.onresize = window.onload = function() {
var header = document.querySelector('.header')
width = this.innerWidth;
height = this.innerHeight;
header.innerHTML = width + 'x' + height; // For demo purposes
header.style.setProperty('height', height + 'px')
header.style.setProperty('width', width + 'px');
//header.style.height = height + 'px';
//header.style.width =width + 'px';
}
fiddle
I am trying to change the width and height of a DIV dynamically using variables in javascript. My code below is not working for me.
div_canvas.setAttribute('style', "width: '+w_resized+'px");
div_canvas.setAttribute('style', "height: '+h_resized+'px");
Where w_resized and h_resized are variables.
Using setAttribute will override the previously provided values.... you can use the style property like
div_canvas.style.width = w_resized + 'px';
div_canvas.style.height = h_resized + 'px';
Return the width property:
object.style.width
Set the width property:
object.style.width="auto|length|%|initial|inherit"
same for height
Use like this.
div_canvas.style.width = w_resized+'px';
div_canvas.style.height = h_resized+'px';
//HEIGHT
function upBig(id,ud) {
var div=document.getElementById(id);
var h=parseInt(div.style.height)+ud;
if (h>=1){
div.style.height = h + "px";
}
}
//WIDTH
function upBig2(id,ud) {
var div=document.getElementById(id);
var h=parseInt(div.style.width)+ud;
if (h>=1){
div.style.width = h + "px";
}
}
http://jsfiddle.net/1cotj5o5/65/
Now I have working on window load code, but can't make it work with window resize (height values will increase if I repeat the same function for resize event). Array is to show initial values after onload completed.
var arr = [];
window.onload = function() {
var newsBlocks = document.getElementsByClassName('news');
for (var i = 0; i < newsBlocks.length; i++) {
var newsBlock = newsBlocks[i];
var left = newsBlock.getElementsByTagName('article')[0];
var right = newsBlock.getElementsByTagName('article')[1];
var height = Math.max(left.offsetHeight, right.offsetHeight);
left.style.height = right.style.height = height.toString() + 'px';
arr.push(left.style.height);
console.log(arr);
}
};
Here is html:
<div class="main">
<section class="news">
<article>
<img src="images/t.png">
<h2>Heading</h2>
test text
</article>
<article>
<img src="images/t.png">
<h2>Heading</h2>
a lot of test text here
</article>
</div>
Pure JavaScript solution is appreciated. Thanks in advance for a help!
You should re-organize your code to be able to repaint the whole screen any time, and hook on the resize event, see: JavaScript window resize event
Resize event is called also on mobile devices, when they change orientation.
<div id=div1></div>
<script>
div1.style.height = (your preffered height)
</script>
same you can do with width.
it works for me ...
try the following code. It is working for me.
var buffer = 20; //scroll bar buffer
var divId = document.getElementById('yourDivID');
function pageY(elem) {
return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;
}
function resizeDiv() {
var height = document.documentElement.clientHeight;
height -= pageY(divId) + buffer;
height = (height < 0) ? 0 : height;
divId.style.height = height + 'px';
}
window.onresize = resizeDiv;
I come to you with a tricky question:
Imagine you have the following basic structure:
<div><p>hello</p></div>
Now assume that div has display:block; and width:200px;.
Using javascript, how would you check what font-size gives you a 'hello' as big as possible without horizontal overflow (in the case of one word) or jumping to a 2nd line in case of a sentence or group of words?
I can't think of a way to measure the space occupied by text so that it can then be checked against that of the parent container, let alone checking if an element is overflowing or linejumping.
If there is a way, I'm sure this is the right place to ask.
Take a look at FitText
It is open source on github as well.
If you are interested in typography you might want to check out their other project called Lettering.js
There may be a method that's not as crazy, but this should be as precise as possible. Essentially, you have a div that you use to measure its width and incrementally increase the text content until it exceeds the width of the target div. Then, change the target div's <p>'s font size to the measuring div's minus 1:
http://jsfiddle.net/ExplosionPIlls/VUfAw/
var $measurer = $("<div>").css({
position: 'fixed',
top: '100%'
}).attr('id', 'measurer');
$measurer.append($("<p>").text($("p").text()));
$measurer.appendTo("body");
while ($measurer.width() <= $("#content").width()) {
$("#measurer p").css('font-size', '+=1px');
console.log($("#measurer").width());
}
$("#measurer p").css('font-size', '-=1px');
$("#content p").css('font-size', $("#measurer p").css('font-size'));
$measurer.remove();
Quick and dirty
fiddle
Set p's style to display: inline then run this
var dWidth = $("div").width();
var pWidth = $("p").width();
var starting = 1;
while (pWidth < dWidth) {
$("p").css("font-size",starting+"em");
pWidth = $("p").width();
starting = starting + .1;
}
Try this:
Auto-size dynamic text to fill fixed size container
(function($) {
$.fn.textfill = function(options) {
var fontSize = options.maxFontPixels;
var ourText = $('span:visible:first', this);
var maxHeight = $(this).height();
var maxWidth = $(this).width();
var textHeight;
var textWidth;
do {
ourText.css('font-size', fontSize);
textHeight = ourText.height();
textWidth = ourText.width();
fontSize = fontSize - 1;
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
return this;
}
})(jQuery);
$(document).ready(function() {
$('.jtextfill').textfill({ maxFontPixels: 36 });
});
<div class='jtextfill' style='width:100px;height:50px;'>
<span>My Text Here</span>
</div>
new jsFiddle Demo (updated 3/22/13)
I would just keep increasing the font size until the clientWidth or clientHeight changed. However, this becomes unreliable when using the actual element itself. To handle that situation, it is possible to create a span on the fly and then monitor the span's dimensions in order to properly retain the actual element's original sizes.
js
var adjuster = document.getElementById("adjust");
adjuster.onclick = function(){
var p = document.getElementById("p");
var text = p.innerText;
var s = document.createElement("span");
s.innerText = text;
p.innerHTML = "";
p.appendChild(s);
var h = p.clientHeight;
var w = p.clientWidth;
var size = 10;
while(true){
size++;
s.style.fontSize = size + "px";
if($(s).height() > h || $(s).width() > w){
size-=2;//rollback to no height change
s.style.fontSize = size + "px";
break;
}
}
p.style.fontSize = s.style.fontSize;
p.removeChild(s);
p.innerText = text;
};