Allow scrolling until last element - javascript

I have a div with some element inside it and I would like to allow the scrolling of the div until the last element.
This is what happens when I scroll:
And this is how I would like to make it:
Is it possible to do it?

Well, it is quite simple without any javascript:
HTML:
<div>
<section>hello</section>
<section>hello</section>
<section>hello</section>
<section>hello</section>
<section>hello</section>
<section>hello</section>
<section>hello</section>
</div>
CSS:
section { height: 100px; }
section:last-child { height: 100%; }
div {
overflow: scroll;
height: 400px;
border: 1px solid black;
}
See fiddle. The concept is just to use the parent div height as a height for the last item.

Try achieve this using JS. Set a bottom margin to a last category equal to wrapper height minus last category height.
var wrapperHeight = $("#wrapper").innerHeight();
var lastCategory = $(".category:last-child");
var lastCategoryHeight = lastCategory.height();
var bottomMargin = wrapperHeight - lastCategoryHeight;
lastCategory.css({margin: "0 0 "+bottomMargin+"px 0"});
DEMO

Also it can be done with scrollIntoView, by scrolling into view the last element, this is the JS snippet:
items = document.querySelectorAll("section");i = items[items.length-1];i.scrollIntoView();
And this is the jsfiddle code

Related

How to use Jquery to remove an overflowing element?

Pretty simple problem, but I can't find a solution. This plugin claims to do it, but I can't get it to work on my site at all, not as a called script, not inline, nothing. So, I have two columns of divs, the ones on one side larger than the other. I have set it up so the second column container will match the height of the first (which is determined elsewhere and thus varies) and set it to overflow:hidden, but what I want to do do is to remove the overflowing divs entirely so it always ends on the last complete div. Here's the fiddle: https://jsfiddle.net/bw2v39ru/2/
This is the JS to equalize the heights $('.row2').css('height', $('.row1').height()+'px');
In that example, only two of he block2 spans should be visible and the overflowing ones removed completely instead of leaving half a block.
Try this: https://jsfiddle.net/bw2v39ru/9/
Besides the code below - you will have to e.g. insert a <br style="clear:both;" /> in the parent DIV since the children has float: left
$('.row2').css('height', $('.row1').height());
var maxHeight = $("#main").outerHeight();
$("#main span").each(function() {
var elm = $(this);
if (elm.offset().top + elm.height() > maxHeight)
elm.remove();
});
as promised, here is my answer. Custom build jsfiddle from pure JavaScript.
https://jsfiddle.net/www139/vjgnsrpg/
Here is a code snippit for you. It assumes that all of your block2 elements have a fixed height. Also I changed the .row1 and .row2 classes to ids to make the solution easier to create. Feel free to change it back but remember to use document.getElementsByClassName('class')[i] instead.
//make sure you execute this script onload inside a jquery document ready or window.onload
//get the rendered height of both rows
//enter margin for blocks here
//this also assumes that the height of your block1 and block2 elements are fixed
var margin = 5;
var rowOneHeight = document.getElementById('row1').offsetHeight;
//get height of block2 element including vertical margin (multiplied twice)
var blockTwoHeight = document.getElementById('row2').getElementsByClassName('block2')[0].offsetHeight + 2 * margin;
var howManyBlocksCanFit = Math.floor(rowOneHeight / blockTwoHeight);
var numberOfBlocks = document.getElementById('row2').getElementsByClassName('block2').length;
for (var i = 0; i != numberOfBlocks - howManyBlocksCanFit; i++) {
document.getElementById('row2').removeChild(document.getElementById('row2').lastElementChild);
}
#main {
width: 240px;
}
#row1 {
float: left;
}
#row2 {
float: right;
overflow: hidden;
}
.block1 {
display: block;
margin: 5px;
width: 100px;
height: 50px;
border: 1px solid red;
}
.block2 {
display: block;
margin: 5px;
width: 100px;
height: 100px;
border: 1px solid red;
}
<div id="main">
<div id="row1">
<span class="block1"></span>
<span class="block1"></span>
<span class="block1"></span>
<span class="block1"></span>
<span class="block1"></span>
</div>
<div id="row2">
<span class="block2"></span>
<span class="block2"></span>
<span class="block2"></span>
<span class="block2"></span>
<span class="block2"></span>
</div>
</div>
Hope this helps you, please tell me if there was something I didn't understand in your question to improve my answer.
I programmed it for you, this works after your existing JS code line:
var row2 = $('div.row2'),
block2elements = row2.children('span.block2');
// Function to use also for other situations
function calculateElementsHeight(elements) {
var height = 0;
$.each(elements, function(i, elementRaw ){
height += $(elementRaw).height();
})
return height;
}
for(var i = 0; block2elements.length > i; i++) {
block2elements = row2.children('span.block2'); // Get new state of the block2 elements
if(row2.height() < calculateElementsHeight(block2elements)) {
block2elements.last().remove();
}
}

Div height doesn't get recalculated on resize

It works perfectly when I refresh the page, but when I resize it doesn't recalculate the div height.
JSFIDDLE
$(document).ready(function() {
var selectorsArray = ['home', 'about', 'portfolio', 'contact'];
responsiveResize(selectorsArray);
$(window).resize(function(){
var selectorsArray = ['home', 'about', 'portfolio', 'contact'];
responsiveResize(selectorsArray);
});
});
function responsiveResize(selectorsArray){
$.each(selectorsArray, function( index, value ) {
var cntcnter = $('#'+value+' .content-container');
var height = $('#'+value+' .content-container').height();
console.log(height);
cntcnter.css({'height': height+'px', 'margin-top': '-'+(height/2) +'px'});
});
}
The reason it's not working is because on the first run, you set a height to the container. On the second run, it already has a height set so it's always the same value. If the text overflows the container, it's not affecting the new height in this case.
If you want to keep using your code, you need to clear/remove the height you added on the previous run.
You can use this
var height = $('#'+value+' .content-container').css('height', '').height();
Like Chris Empx mentioned, this is easily obtainable with CSS.
Also, you could optimize the code like this fiddle
i wonder why you want to do that with jquery.
i would do that in css.
like that
<div class='container'>
<div class='column col 12'>
<p>Your Inputs here</p>
</div>
<div class='clear'></div>
</div>
then this in css
.container {
margin: 0 auto;
width: 960px;
}
.col-12{
width: 100%;
}
.clear {clear: both;}
.column {padding: 0 .8em; float:left;}
col-6 would be width:50%
col-3 would be width:25%

set a newly created div on top of the older divs

I have a bunch of divs inside a container. The position of the content divs is relative, because I want them to appear one below the other and their height is unknown.
These divs are created dynamically (appendchild) inside the container div. Now, each div appears on the end (bottom) of the stack but my requirement is that the divs have a "newest first" option too, that is, each new div appears on top, not on bottom of the content divs (if the user selects the "newest first" in the settings).
html:
<div class="container">
<div id="div1" class="content">aaa<br>aaa</div>
<div id="div2" class="content">bbb<br><br>bbb</div>
<div id="div3" class="content">ccc</div>
<div id="div4" class="content">ddd</div>
</div>
css:
.container {
position: absolute;
top: 10px;
left: 10px;
right: 10px;
bottom: 10px;
border: 1px solid red;
}
.content {
position: relative;
top: 0px;
left: 5px;
width: 200px;
height: auto;
border: 1px solid blue;
margin: 3px;
}
http://jsfiddle.net/jk559/1/
so I'd like the end-user visible order to be: div4, div3, div2, div1.
How can I achieve this? (css/js)
preferrably no jquery.
thanks in advice!
Pure css solution:
Use flexbox to achieve this.
.container {
display:flex;
flex-direction:column-reverse;
justify-content: flex-end;
align-content: flex-end;
}
Updated fiddle here.
Read more information here.
try this
theParent = document.getElementById("theParent");
theKid = document.createElement("div");
theKid.setAttribute("id","div5");
theKid.setAttribute("class","content");
theKid.innerHTML = 'eee';
// append theKid to the end of theParent
theParent.appendChild(theKid);
// prepend theKid to the beginning of theParent
theParent.insertBefore(theKid, theParent.firstChild);
Demo Fiddle http://jsfiddle.net/jk559/4/
You can easily do it with JQuery with the following function.
$('.container > div').each(function() {
$(this).prependTo(this.parentNode);
});
UPDATED FIDDLE
As you mentioned in the question, I will try to attain the expected output with the pure javascript.
You can insert content in the beginning simply using .prepend() .
$(".container").prepend("<div id='div5' class='content'>eee</div>");
Demo
JS FIDDLE UPDATED DEMO
Use prepend() to add as first child of an element
/* $( ".container" ).prepend( "Your div with id here" ); */
/* Example */
$( ".container" ).prepend( "<div id='div5' class='content' >div5 on top </div>" );
Take a look at this answer about reordering dom items.
Basically, you have to maintain a state that decides the ordering. When you insert items (see insertItem below) you append or prepend based on the state. When the user selects the newest first option (see newFirst below), you first reverse the dom elements and then flip the state so that subsequent insert happen at the right place.
var newFirst = false;
var list = document.getElementById('my-list');
function newFirst() {
var items = list.childNodes;
var itemsArr = [];
for (var i in items) {
if (items[i].nodeType == 1) { // get rid of the whitespace text nodes
itemsArr.push(items[i]);
}
}
itemsArr.reverse();
for (i = 0; i < itemsArr.length; ++i) {
list.appendChild(itemsArr[i]);
}
newFirst = !newFirst;
}
function insertItem(content) {
var item = document.createElement("div");
item.setAttribute("class","content");
item.innerHTML = content;
if(newFirst) {
list.insertBefore(item, list.firstChild);
} else {
list.appendChild(item);
}
}
try this :
$("div[id*=div]").sort(function(a,b){
if(a.id > b.id) {
return -1;
} else {
return 1;
}
}).each(function() {
var elem = $(this);
$(".container").append(elem);
});
this will sort your divs inside container like this : div4, div3, div2, div1
if you want change the order to : div1, div2, div3, div4 just change if(a.id > b.id) to if(a.id < b.id)
you can add a link called change order then call this code when you click on it

How to set a div height according to another div height using javascript?

I have 2 divs. Since div 1 could be longer, i.e. infinite scroll div, I want to make div 2 the same height with div 1 using javascript. I tried to use the code below, but it does not work. Why?
javascript:
<script type="text/javascript">
document.getElementById("div2").setAttribute("height",document.getElementById("div1").clientHeight);
</script>
my divs:
#div1 {
width: 700px;
background: #FFF;
overflow: hidden;
float: left;
}
#div2 {
width: 300px;
background-image: url(../images/user_panel.png);
background-repeat:repeat-y;
}
What about this:
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
div2.style.height = div1.style.height; // Might have to add +"px" here.
Just from the top of my head.
This should do the trick:
document.getElementById("div2").style.height=document.getElementById("div1").clientHeight+'px';
the setAttribute function is a DOM function to add a new attribute to an HTML element. You are trying to add the height on a div. That would have the effect:
<div id="div2" height="...">...</div>
But HTML does not define such an height HTML element attribute.
What you are looking for is to set the style of the DOM element. That would be the style DOM element property. And inside the style you have the height property that you must set:
document.getElementById("div2").style.height = document.getElementById("div1").clientHeight + "px";
In the above code sample you might also think about div1's padding (probably bringing it into the computation). This is because clientHeight includes the padding but style.height does not.

How to get div's content height

My div has a styling position:absolute, and as a result, it doesn't expand if the content is higher than it's height.
Therefore, I thought that a solution would be if I find what the is the actual content's height, and assign the height to the div with the position:absolute styling.
Any idea how to do it? or maybe an idea how to make an absolute div to expand according to its content.
Thanks in advance!
Element.scrollHeight should do the job.
Here's an awful way to get the height of the container. We're basically cloning the whole div, setting the position so that it has height, checking that height, and then removing it:
$(function () {
var clone = null;
alert( clone = $('.test').clone().css('position', 'static').appendTo(".container").height());
clone.remove();
});
Here's the fiddle: http://jsfiddle.net/vPMDh/1/
It should expand even if being absolute.
check you don't have a height: xxpx
if so, change it to min-height
As you've said "it doesn't expand if the content is higher than it's height." I guess you have a fixed height set on it.. if you do need this for some reason try using min-height instead.
Have a look at this fiddle.
<div class="classname">
Some content....
<p style="clear:both">&nbsp</p>
</div>
use a clearfix hack. heres the link
and add clearfix to you div
example
in your style sheet
<style>
.clearfix:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.clearfix {
display: inline-block;
}
html[xmlns] .clearfix {
display: block;
}
* html .clearfix {
height: 1%;
}
</style>
...
and in your div add clearfix the class
<div class="clearfix">
//some html tags
</div>
Thanks for contributing your question. If you use this:
$(document).ready(function(){
var x = $("#container").height();
alert(x);
//if not works then
var y = $("#container").outerHeight();
alert(y);
});
I think it is easy as clean code to find the height of any div if you do not apply the div's height too.
similar solution to #MattDiamant, but with vanilla JS and without creating a clone:
function getDivHeight(posAbsoluteDiv) {
const heightBackup = posAbsoluteDiv.style.height;
posAbsoluteDiv.style.height = 'auto';
const contentHeight = posAbsoluteDiv.getBoundingClientRect().height;
posAbsoluteDiv.style.height = heightBackup;
return contentHeight;
}

Categories

Resources