Here's the code on JSFiddle.
Here's the script.
function toggle(divId, tog) {
var div = document.getElementById(divId);
div.classList.toggle(tog);
}
function toggleSize(divId, tog, textId) {
var div = document.getElementById(divId);
div.classList.toggle(tog);
div.getElementsByClass(tog)[0].style.height = window.getComputedStyle(textId).getPropertyValue('height');
}
What I tried doing is get the height value of the contained text, and assign that to the outer div.
But, the height is not updating.
Another way to word it is that I want the height to adjust to the overflowed content.
Any ideas?
Related
I've got some code that adds a CSS class to an element when the user scrolls to a certain amount, to make a sticky menu bar (The distance to scroll is dependant on screen resolution so is calculated within the JQuery) - I want to add a CSS value to this class (.header_scroll) so that it changes the height of the element the class is being assigned to on scroll, to the height of another dynamic height element (#nav_wrap)
jQuery("document").ready(function($){
//Find the height of the header
var headHeight = $("#header_wrap");
var headerHeight = headHeight.innerHeight();
//Find the height of the nav bar
var menuFindHeight = $("#nav_wrap");
var menuHeight = menuFindHeight.innerHeight();
//Add value to class
$(".header_scroll").css({"height": menuHeight});
//Add class on scroll
var nav = $('#header_wrap');
$(window).scroll(function () {
if ($(this).scrollTop() > ( headerHeight - menuHeight )) {
nav.addClass("header_scroll");
} else {
nav.removeClass("header_scroll");
}
});
});`
The code to add the class is working fine, however no matter what variations on this I try, the:
//Add value to class
$(".header_scroll").css({"height": menuHeight});
Section will just not do anything at all. Looking in inspect element in chrome I'd expect to see
height: xxxpx;
appear in .header_scroll but it isn't
$(".header_scroll").css({"height": 200});
This will not add a height property to your CSS rule. Instead it will add style="height: 200px;" to the .header_scroll HTML element(s).
So you would end up with an HTML element like:
<div class="header_scroll" style="height: 200px;"></div>
Maybe you can't get the right value of headerHeight, that why it doesn't appear in your inspect tools.
Check that you get the correct height of your #headHeight element and try this:
$(".header_scroll").height(headerHeight);
I want to resize the textarea to fit the contents of the text area.
I am currently using the following code to do that:
var element = document.getElementById(event.target.id);
var content = $(this).val().trim();
if (content == "") {
$(this).animate({
width: element.scrollWidth,
height: element.scrollHeight
}, 100);
}
When I enter nothing. I expect the textarea to become smaller in size and eventually disappear.
But it is expanding instead. :(
JSFiddle: http://jsfiddle.net/7vfjet1g/
I think what you're looking for is an elastic text area. There are a few JavaScript libraries that provide this functionality:
https://github.com/chemerisuk/better-elastic-textarea
https://github.com/chrisgeo/elastic-textarea
http://unwrongest.com/projects/elastic/
It's not much code, but a careful combination of JavaScript and CSS. If for some reason you don't want to add another library to your project, or this doesn't fit your requirement, it may point you in the right direction. Good luck.
I tested out your existing code, and the values that scrollWidth and scrollHeight were giving you were much bigger than the size of the actual text.
One way to get the size of the actual text is to create a span with the same font styling as the text area, copy over the value of the textarea to it, then append the span to the document. You can then use getBoundingRect() to get the dimensions of the span, and thus the dimensions of the text in your textarea.
NOTE: I changed the id of your enclosing div. It had the same id as the textarea, and ids are supposed to be unique. Having two elements with the same id could cause problems with the javascript. Here's the jsfiddle: https://jsfiddle.net/yog8kvx7/7/. And here's the updated blur function:
$('.notesArea').blur(function (event)
{
var content = $(this).val().trim();
var element = document.getElementById(event.target.id);
// Create span to calculate width of text
var span = document.createElement('span');
// Set position to absolute and make it hidden
// so it doesn't affect the position of any other elements
span.style.position = 'absolute';
span.style.visibility = 'hidden';
// Only set to whitespace to pre if there's content
// "pre" preserves whitespace, including newlines
if (element.value.length > 0)
span.style.whiteSpace = 'pre-wrap';
// Copy over font styling
var fontStyle = window.getComputedStyle(element);
span.style.display = 'inline-block';
span.style.padding = fontStyle.padding;
span.style.fontFamily = fontStyle.fontFamily;
span.style.fontSize = fontStyle.fontSize;
span.style.fontWeight = fontStyle.fontWeight;
span.style.lineHeight = fontStyle.lineHeight;
span.innerHTML = element.value;
// Add to document and determine width
document.body.appendChild(span);
var rect = span.getBoundingClientRect();
var width = rect.width;
var height = rect.height;
// Remove span from document
span.parentNode.removeChild(span);
$(this).animate({
width: width,
height: height
}, 100);
});
And if you want to account for the little sizing handle, so it doesn't cover the text, you can just add an offset to the width to account for it.
I have a div with a static size. Sometimes longer text than the div will be placed there. Is there anyway to achieve the text fitting the div width at all times through JavaScript alone? I am aware there are jQuery fixes but need a pure JS solution in this case.
Even if you have a link to a demo/tutorial that would be helpful, thanks.
Here you go, this should do what you want: JSFiddle
Basically the key here is to check the output.scrollHeight against output.height. Consider the following setup:
HTML:
<button onclick="addText(); resizeFont()">Click Me to Add Some Text!</button>
<div id="output"></div>
CSS:
div {
width: 160px;
height: 160px;
}
This creates a square div and fills it with a randomly long string of text via the addText() method.
function addText() {
var text = "Lorem ipsum dolor amit",
len = Math.floor(Math.random() * 15),
output = document.querySelector('#output'),
str = [];
for (; --len;)
str.push(text);
output.innerHTML = str.join(', ');
}
The magic lies in the resizeFont() function. Basically what this does is, once the text has been added, it sets the fontSize of the div to be equal to its own height. This is the base case for when you have a string of 1 character (i.e. the fontSize will equal the height). As the length of your string grows, the fontSize will need to be made smaller until the scrollHeight equals the height of the div
function resizeFont() {
var output = document.querySelector('#output'),
numRE = /(\d+)px/,
height = numRE.exec(window.getComputedStyle(output).height)[1],
fontSize = height;
// allow div to be empty without entering infinite loop
if (!output.innerHTML.length) return;
// set the initial font size to the height of the div
output.style.fontSize = fontSize + 'px';
// decrease the font size until the scrollHeight == height
while (output.scrollHeight > height)
output.style.fontSize = --fontSize + 'px';
}
The nice thing about this method is that you can easily attach an event listener to the resize event of the window, making the text dynamically resize as the user changes the window size: http://jsfiddle.net/QvDy8/2/
window.onload = function() {
window.addEventListener('resize', resizeFont, false);
}
I create one div#sresult_container dynamically and append no of div to that div. and all appended div have different text. so i can retrieve the width of div#sresult_container but i try to that increase the width of div#sresult_container 10px before it display on the view port. how can i do this plese help me?
my code is below:
var $sresult_container = $('<div id="sresult_container"></div>');
AND after that i append the some divs as children of div#sresult_container.
and append to body.
$('body').append($sresult_container);
var Setwidth = $('#sresult_container').outerWidth() + 10;
$('#sresult_container').css('width',Setwidth + 'px');
so here first load original width after that load the modified width. so how can do directly load the modified width.
First of all #sresult_container must have a pre-defined width.
#sresult_container {
width: 100px;
}
$('<div id="sresult_container">text</div>').appendTo('body');
$('#sresult_container').css('width', function () {
return ($(this).outerWidth(true) + 10) + 'px';
});
http://jsfiddle.net/xBZT7/14/
http://jsfiddle.net/xBZT7/15/
I have multiple divs in my body which need the same style:
<div class="box"></div>
I have a javascript that calculates the height of the browser window viewport height.
I want to apply that height to all my "box" classed divs.
<script type="text/javascript">
var box = document.getElementsByClassName('box')[0];
var height = (window.innerHeight) ? window.innerHeight: document.documentElement.clientHeight;
box.style.height=(height)+'px';
</script>
This works, but only with one div, it doesn't make the second "box" div the same height as the previous. If I change the number in square brackets from 0 to 1 it applies the height to the second div. Also, if I make a second copy of the javascript so that the first script has [0] and the second [1] it applies the height to both divs. I can't delete the square brackets because then the javascript doesn't work at all. I have also tried to get the name with getElementsByTagName with no success.
How can I make this javascript apply the same height to all the divs with "box" class? Or is there another way to do what I try to do?
try the following:
var elems = document.getElementsByClassName('box'),
size = elems.length;
for (var i = 0; i < size; i++) {
var box = elems[i];
var height = (window.innerHeight) ? window.innerHeight: document.documentElement.clientHeight;
box.style.height=(height)+'px';
}
Demo: http://jsfiddle.net/JRdHD/
A simple way would be to document.write the style in the html,
while the page is being read, after the link elements are defined.
<script>
document.writeln('<style>div.box{height:'+
document.documentElement.clientHeight+'px;}'+
'<\/style>');
</script>
</head>
<body...