Resizing child DIV equal to parent DIV - javascript

I have a DIV with width 400px and height 200px. Inside this div is another div with some text at position 50,50 and font-size 14px;
When the parent DIV resizes (for example to 600px x 300px), i want that the text-size inside the child DIV resizes too (to a larger font-size), equal to the resized parent DIV.
How can i do that with jQuery and HTML?

make the child div width and height 100%
childDiv {
display:block;
width: 100%;
height: 100%;
position:relative //so you dont lose the positioning of your text
}

when the parent dives size becomes (600 / 300) from (400 / 200) for example, you should apply a javascript function to the child div like so
function resizeFont(parentElementId, childElementId, newWidth) {
currWidthParentElement = parseFloat( $(parentElementId).width() ); // get current width
currChildFontSize = parseInt( $(childElementId).css('font-size') ); // get font size for child
percentaRaise = (newWidth - ceil(currWidthParentElement)) * (100/ceil(currWidthParentElement)); // calculate how much parent increase
// calculate and apply new font size
newFontSize = currChildFontSize * percentaRaise/100 + currChildFontSize;
$(childElementId).css(newFontSize);
}
is seems tricky but is simple algebra. I hope thihs will help you

http://codepen.io/rafaelcastrocouto/pen/EiFIL
var div = $('div');
$(window).on('resize', function(){
var u = div.width() / 200;
div.css('font-size', u +'em');
});

There is an extension for jquery that allows resize to be fired on elements like it would on the window itself.
The extension: Jquery Resize Plugin
So something like this will do the trick:
$("#parent").resize(function(){
var newFontSize = $("#parent").height() * 0.07
$("#child").css("font-size",newFontSize +"px");
});
Check out this JsFiddle for an example: http://jsfiddle.net/Mm3jr/1/

Related

How to set the font-size to 100% the size of a div?

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);
}

get percentage scrolled of an element with jquery

I'm trying to get an div to animate 0% - 100% relative to the percentage scrolled of an element.
Now I've set up a few variables, but I'm having trouble trying to calculate the height of one by percentage.
We can set the starting width quite easily and detect the scroll easily enough too, as can we get the height of the element that'll trigger the animation, I just can't get it as a percentage.
If I can figure out how to return the percent of conheight scrolled then this should be easy.
$(window).scroll(function() {
// calculate the percentage the user has scrolled down the page
var scrollPercent = ($(window).scrollTop() / $(document).height()) * 100;
$('.bar-long').css('width', scrollPercent +"%" );
});
Here's a jsfiddle, http://jsfiddle.net/SnJXQ/
This is animating bar-long based on the percent scrolled of the body element.
Animates from 0% - 100% (well, it doesn't really, but I can't figure out why).
What I'd like to do is get scroll percent of the .post div, then animate bar-long relative to that.
ie. Scrolled 10% of .post, .bar-long is 10% width, scrolled 70% of .post, .bar-long is 70% width.
Demo
Your problem is the same as How to get horizontal scrolling percentage of an HTML element in JavaScript?, but vertically.
Then, to get the vertically scrolled percentage, use
/* JS */ var scrollPercentage = 100 * containeR.scrollTop / (containeR.scrollHeight-containeR.clientHeight);
/*jQuery*/ var scrollPercent = 100 * $(containeR).scrollTop() / ($(containeD).height() - $(containeR).height());
In your case, containeR = window; containeD = document:
var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
Ok I see what you are trying to achieve....in fact I just did something very similar. Most solutions I found out there also were only for full page examples with window or document properties. Instead I needed this in a specific div which in my case was actually used to update the horizontal position of another div.
First, you are going to want the scroll event attached to your $('.post')
Next, the height of the $('.content') is going to equal your actual Scroll Height
Lastly, apply your percentage formula : (Y / (scrollHeight - postHeight)) * 100 = scrollPercent
So instead of using document or window attributes your code should be as follows:
$('.post').scroll(function() {
var currY = $(this).scrollTop();
var postHeight = $(this).height();
var scrollHeight = $('.content').height();
var scrollPercent = (currY / (scrollHeight - postHeight)) * 100;
});
You can find the fiddle here: JS Fiddle For Div Scroll Percentage
The current project where I have implemented this is located here: Vertical Scroll Drives Horizontal Position
I hope this solves your problem :)
Let's say you want to keep track of the scroll of some document found in some IFrame in your page.
object.addEventListener("scroll", documentEventListener, false);
Then your event listener should look like this:
function documentEventListener(){
var currentDocument = this;
var docsWindow = $(currentDocument.defaultView); // This is the window holding the document
var docsWindowHeight = docsWindow.height(); // The viewport of the wrapper window
var scrollTop = $(currentDocument).scrollTop(); // How much we scrolled already, in the viewport
var docHeight = $(currentDocument).height(); // This is the full document height.
var howMuchMoreWeCanScrollDown = docHeight - (docsWindowHeight + scrollTop);
var percentViewed = 100.0 * (1 - howMuchMoreWeCanScrollDown / docHeight);
console.log("More to scroll: "+howMuchMoreWeCanScrollDown+"pixels. Percent Viewed: "+percentViewed+"%");
}

element.height returns visible height - I want total?

So apparently this is only happening to me - and I can't think why but if it works, I'm happy :)
I have a full screen slideshow and I have created a function that will vertically center any images that are too large.
function fixImages(){
maxheight = $('.index-slide-container').height();
$('.index-slide-container img').each( function(index, ele){
if (ele.height > maxheight){
offset = ( maxheight - ele.height ) / 2;
$(ele).css('top', offset + 'px');
}
});
}
fixImages();
However, ele.height returns the height of the visible part of the image (the height of it's container, as it has overflow:hidden, even though when I console.log(ele) and expand the element, 'height' is clearly the correct value.
I have also tried $(ele).height(), $(ele).css('height'), $(ele).outerHeight() and ele.clientHeight; all of which return the same.
Thanks
I made some tests, and $('img').height(); is giving me the right height of the picture.
If you wish to center the picture vertically why don't you use the absolute positioning with css like this for example :
.index-slide-container img {
position:absolute;
top:50%;
}
And than, you could set the negative margin programmatically with jQuery :
$('.index-slide-container img').each( function(i, e){
var height = $(e).height() / 2;
$(e).css({'margin-top':'-'+height});
});

set the width dynamically of element which create dynamically

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/

Dynamic Image Resizing

I have an image on a webpage that needs to be stretched to fit the available space in the window whilst maintaining its proportion. Here's what I've got:
http://www.lammypictures.com/test/
I would like the large image to proportionally stretch to match the height and widths of the browser, minus the size of the divs to the left and bottom.
So the problem is 2 fold really; first i need to get the max height and width minus the link and image bars, secondly i need to resize the image on a browser resize whilst maintaining proportions.
Any help would be much appreciated.
Cheers
CIP
You could try using jQuery ui scaling effect:
$(document).ready(function () {
resizeImage(); // initialize
$(window).resize(function () {
resizeImage(); // initialize again when the window changes
});
function resizeImage() {
var windowHeight = $(window).height() - $('#nav').height(),
windowWidth = $(window).width(),
percentage = 0;
if (windowHeight >= windowWidth) {
percentage = (windowWidth / $('#image').width() ) * 100;
}
else {
percentage = ( windowHeight / $('#image').height() ) * 100;
}
$('#image').effect('scale', { percent : percentage }, 1);
};
});
Tested and works great, however, a few tweaks maybe needed to get it just the way you like it.
You may just not setup the image element width and height attributes, and write next styles:
.hentry img { max-width: 100%; }
And it will shrink relative to the minimum side.
P.S. But not in position: absolute; block which not have any size. Set up the parent block to relative positioning.

Categories

Resources