Calculate height left for paragraph / subtract elements in JavaScript - javascript

I want to crop text and found ways to do that.
The problem is they work on height and i don't know the height because the heading above can have 1, 2, 3... lines.
So i need to get the height of the outer element and subtract the heading height.
var list = document.body.getElementsByClassName("cropText");
for (var i = 0; i < list.length; i++) {
cropTextToFit(list[i]);
}
function cropTextToFit (o) {
var containerHeight = o.clientHeight;
var head = document.getElementsByTagName("H2");
var headHeight = head.clientHeight;
console.log(containerHeight);
console.log(headHeight);
}
cropText is the article tag where the heading and the paragraph are in.
headHeight shows "undefined" and "containerHeight" is wrong...

Firstly you need to find the <H2> tag within the cropText element (o in your function), document.getElementsByTagName("H2") will return an array of all the <H2> s in the document
Presuming there is only one h2 inside the cropText element you need something like
var head = o.querySelector('h2');
Also, to work out the total h2 height you will need offsetHeight + the height of the top and bottom margins

getElementsByTagName returns more objects and param clientHeight not avaliable. Use head[i]

Related

jQuery: css margin based on the amount of elements in container?

I'm trying to create a simple collage creator using jquery.
what I need to do is to have a margin of 1% between each element (collage).
But at the same time I need the collages to have 0 margin from their container.
I hope that makes sense.
I've created this FIDDLE so you know what I mean.
when you run the code, just click on the button 4 times and you should see the collages being created inside the container perfectly fine BUT there is a margin between their container and its children elements which is not wanted.
Is there any way to sort this issue out?
This is my code:
$('#colBtn').live('click', function(){
$('.lable').show();
$('#reset').show();
$('#fileField').show();
$('#sbs').show();
var width = $('#width').val();
var height = $('#height').val();
$('#main').append('<div class="droppable" style="width:'+width+';height:'+height+';overflow: hidden; position:relative;float:left; margin:1%;"></div>');
$('#layout').text($('#main').html());
return false;
});
What you're looking for is a negative margin.
put another div in your #main div and give it a negative margin.
margin: 0 -1%
This will make it as if it had no margin since you have
overflow: hidden
set to your main container.
Something like this: Fiddle
Hope this gets you closer to your goal ;)
By the above given figure. The main issue seems like figuring out which is the first item and which is the last item of a row. having dynamic number of items in a row.
I just figure out the first item and last item you can use it to adjust margin.
function fix(){
var $item = $('.droppable');
var parentWidth = $item.parent().width();
var itemWidth = $item.outerWidth(true);
var itemInLine = Math.floor(parentWidth/itemWidth);
var totalItems = $item.length;
var rows = totalItems / itemInLine;
var lastItem = 0;
var firstItem = 1;
for(var i = 1; i< rows + 1; i++){
lastItem = i * itemInLine;
$('.droppable:nth-child('+ lastItem +')').css({'margin-top':'0px','margin-right':'0px'});
firstItem = (i * itemInLine) - itemInLine + 1;
$('.droppable:nth-child('+ firstItem +')').css({'margin-top':'0px'});
}
}

Is Javascript an Effective Method of Creating Fluid Layouts?

I'd like opinions on whether or not Javascript is a still a viable and relatively effective method of producing fluid website layouts. I know that it is possible to create fluid layouts with Javascript, but relative to other methods (e.g. CSS3/HTML5) how does it stand up in terms of performance and complexity? The function below represents what I mean. In the function, javascript is being used to find the dimensions of various elements and place other elements accordingly. To see it working, follow this link.
function onPageResize() {
//center the header
var headerWidth = document.getElementById('header').offsetWidth; //find the width of the div 'header'
var insideHeaderWidth = (document.getElementsByClassName('header')[0].offsetWidth + document.getElementsByClassName('header')[1].offsetWidth + document.getElementById('logoHeader').offsetWidth); //find the combined width of all elements located within the parent element 'header'
document.getElementsByClassName('header')[0].style.marginLeft = ((headerWidth - insideHeaderWidth) / 2) + "px"; //set the margin-left of the first element inside of the 'header' div
/////////////////////////////////////////////////////////////////
//justify alignment of textboxes
var subtitleWidth = document.getElementsByClassName('subtitle'); //assign the properties of all elements in the class 'subtitle' to a new array 'subtitleWidth'
var inputForm = document.getElementsByClassName('inputForm'); //assign the properties of all elements in the class 'inputForm' to a new array 'inputForm'
for (i = 0; i < inputForm.length; i++) { //for every element in the array 'inputForm' set the margin-left to dynamically place the input forms relative to eachother
inputForm[i].style.marginLeft = (subtitleWidth[4].offsetWidth - subtitleWidth[i].offsetWidth) + "px";
}
/////////////////////////////////////////////////////////////////
//place footer on absolute bottom of page
if (window.innerHeight >= 910) { //when the page is larger than '910px' execute the following
var totalHeight = 0; //initialize a new variable 'totalHeight' which will eventually be used to calulate the total height of all elements in the window
var bodyBlockHeight = document.getElementsByClassName('bodyBlock'); //assign the properties of all elements in the class 'bodyBlock' to a new array 'bodyBlockHeight'
for (i = 0; i < bodyBlockHeight.length; i++) { //for every instance of bodyBlockHeight in the array, add the height of that element into the 'totalHeight'
totalHeight += bodyBlockHeight[i].offsetHeight;
}
totalHeight += document.getElementById('header').offsetHeight; //finally, to add the height of the only element that has yet to be quantified, include the height of the element 'header' into the 'totalHeight'
/*Set the margin-top of the element 'footer' to the result of subtracting the combined heights of all elements in the window from the height of the window.
This will cause the footer to always be at the absolute bottom of the page, despite whether or not content actually exists there. */
document.getElementById('footer').style.marginTop = (window.innerHeight - totalHeight) - document.getElementById('footer').offsetHeight + "px";
} else {
//if the page height is larger than 910px (approx the height of all elements combined), then simply place the footer 20px below the last element in the body
document.getElementById('footer').style.marginTop = "20px"
}
/////////////////////////////////////////////////////////////////
}
Again, the result of the above function can be viewed at this link.
Thank you to any and all who offer their opinions!
You should be using CSS rather than JavaScript because that is what CSS is designed to do. If you want a fluid layout play around with using percentage widths, floats and media queries.

How to get the real scroll height of div (say, inner text size)

I'm trying to make a auto-scrolling div that go to its top when it reaches the end. But it doesn't work...
function scrollPannel()
{
var pannel = document.getElementById('pannel');
if (typeof scrollPannel.count == 'undefined')
{
scrollPannel.count = 0;
}
else
{
scrollPannel.count += 2;
}
// trouble is here
if ((scrollPannel.count - pannel.scrollHeight) > pannel.clientHeight)
{
scrollPannel.count = 0;
}
pannel.scrollTop = scrollPannel.count;
setTimeout('scrollPannel()', 500);
}
HTML:
<div id='pannel' style="height:200px;overflow:auto" onmouseover="sleepScroll()">
<p>...</p><!-- long text -->
</div>
And after, I will need to find how to stop scrolling when "onmouseover" occures.
EDIT: I did not explained the problem clearly. In fact, I have tried something like:
if (scrollPannel.count > pannel.scrollHeight)
{
scrollPannel.count = 0;
}
The problem is that scrollHeight seems greater than div inner text. So it makes a lot of time to return to the top.
So I need an element property of which I could use the value to compare with my count variable. However I don't know Javascript a lot and I could not find anything. I hope it is as well simple as I think of it.
Try:
// calculate max scroll top position (go back to top once reached)
var maxScrollPosition = element.scrollHeight - element.clientHeight;
// example
element.scrollTop = maxScrollPosition;
That should do what you need.
You could try using the scrollHeight property.
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollHeight
The solution I have involves jQuery, hope that's not a problem.
JavaScript:
var timeout;
function scrollPannel()
{
var divHeight = $("#pannel").height() / 2;
var scrollCount = $("#pannel").scrollTop();
var scrollHeight = $("#inside").height() - 20 - divHeight;
scrollCount += 2;
if ((scrollCount - scrollHeight) > 0)
{
scrollCount = 0;
}
$("#pannel").scrollTop(scrollCount);
timeout = window.setTimeout(scrollPannel(), 100);
}
function scrollStop() {
window.clearTimeout(timeout);
}
HTML:
<div id='pannel' onmouseover="scrollStop();" onmouseout="scrollPannel();">
<p id="inside"></p><!-- long text -->
</div>
Explanation:
jQuery's .height() of the inside element <p> gives us the actual height you're looking for, but it's not enough for reaching the bottom, since that happens before we reach the element's height. A little investigation shows that the "top" of scrollTop() is about half way inside the original div's height. You may need to play around with divHeight to get the exact results you're looking for.
Of course, I also included a method for stopping and continuing scrolling.
Good luck!
You should use scrollHeight property but to call it, you need to use an index like that:
$('#pannel')[0].scrollHeight;
If you set the scrollTop and scrollLeft to really high silly values they only ever get set as their maximum allowed values which I think is what you need? You can then use them to work out the scroll center if you wished.
See snippet example.
var mB = document.getElementById('myBox');
var mR = document.getElementById('myResult');
// Set the top and the left to silly values
mB.scrollTop = 99999999;
mB.scrollLeft = 99999999;
// They will only end up being set as their max
mR.innerHTML = "maxTop="+mB.scrollTop+"<br>maxLeft="+mB.scrollLeft;
// Now take the max values and divide by 2 to scroll back to middle.
mB.scrollTop = mB.scrollTop/2;
mB.scrollLeft = mB.scrollLeft/2;
#myBox{
overflow:auto;
}
#myContent{
border:1px solid black;
background-color:red;
}
<div id='myBox' style='width:300px;height:300px'>
<div id='myContent' style='width:500px;height:800px;line-height:800px;'><center>I am the center of the content</center></div>
</div>
<div id='myResult'></div>
I have got one solution....
function findMaxReach(){
let maxReach =0
document.querySelector('.YourElement').scrollLeft = 100000;
maxReach = document.querySelector('.YourElement').scrollLeft;
document.querySelector('.YourElement').scrollLeft = 0;
return maxReach
}

fill Content(html) in div for fix height and widhth using javascript and jquery

I am getting long text using ajax in json form I want to fill those content in the fix height div
suppose I have div height 500px and width 300px. and font size is 16px
i want any javascript recursive method that can fill data according to height and width of div and can return me remaining text.
if any one can do that then Please provide me solution.
Thanks in Advance
First of all, wrap the text inside a <span> in put it in your <div>. I'm assuming that div is your fixed size element here:
// Be careful about text nodes, or use firstElementChild instead
var span = div.firstChild, text = span.innerText, rest = "";
if (span.offsetHeight > 500) {
var totalLength = 0, markLength, i = 0,
rects = span.getClientRects();
for (; i < rects.length; i++) {
totalLength += rects[i].right - rects[i].left;
if (rects[i].bottom - rects[0].top <= 500)
markLength = totalLength;
}
var mark = Math.floor(text.length * markLength / totalLength);
span.textContent = text.substring(0, mark);
rest = text.substring(mark);
}
The variable rest contains the remaining part.
Beware that this method uses some approximations, and sometimes may not fill the container to the brim. In some unlucky cases, it may even overflow the container, so you have to run it again until you get the correct size.
Why don't just put all in the div and in the div you set
overflow="hidden"
Create a temp div, fix it width and append text until it exceed your height then stop, after that copy all content to the main div
var s = 'Your long long long long long long long long long long content';
var i = 0;
var tmpdiv = $('<div style="width:50px; height:auto; position:absolute; left:-99999px"/>').appendTo(document.body);
while (i < s.length-1 && tmpdiv.height() < 50){
tmpdiv.append(s[i]);
i++;
}
$('#fixdiv').html(tmpdiv.html());

How to apply style to a class in javascript?

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...

Categories

Resources