Ordering divs with javascript - css

I have something like this:
http://s9.postimg.org/wwizuwnq7/Untitled_1.png
And if you see, the divs (Where I marked in green) have a space of some pixel.
And i want if there is a 0-20 pixel space between divs, to order them like this:
http://s23.postimg.org/ky2htcpt7/image.png
So, i started to do this on javascript and i dont know to to continue..
var position = new Array();
$(".post").each(function(){
position[$(this).attr("id")] = $(this).offset().top - $(window).scrollTop();
});
now i have all the position of all the divs, and now i need to check where divs have a space of 0 - 20 pixel, and then i want to take down the higher block.
I not sure if this is the good way, and if now, i need another idea..
Thanks!

I managed to find a method!
var position = new Array();
$(".hblocks").each(function(){
position[$(this).attr("id")] = $(this).offset().top;
});
$.each(position, function(key, value) {
$.each(position, function(key2, value2) {
var space = value2 - value;
if (space <= 20 && space >= -20 && space != 0)
{
var finalSpace = Math.max(value, value2);
var spaceplus = space + 28;
if (finalSpace != value)
{
$("#" + key).css("margin-top",spaceplus + "px");
}
else
{
$("#" + key2).css("margin-top",spaceplus + "px");
}
}
});
});

You can do this by adding a container div around the bottom 2 blocks. That way they will always be in line, regardless of the height of either of the top two blocks. You should try not to use javascript for styling. CSS is very powerful.
Here's a fiddle: http://jsfiddle.net/kVn7x/
HTML:
<div>
<div style='height:100px;'></div>
<div style='height:200px;'></div>
</div>
<div style='clear:left'>
<div style='height:80px;'></div>
<div style='height:80px;'></div>
</div>
CSS:
div div{background:red; width:150px; display:inline-block; margin:5px; float:left; clear:none}

Can't you simply add a bottom margin to the selected element in CSS?
#element {
margin-bottom: 20px;
}

Your answer would be some king of javascript+css coding to verify height of elements .. work on em then re-arrange them.
Stop trying to figure out by yourself, try using Masonry or jQueryEqualHeight explained on CSSTrick.
What is Masonry?
Masonry is a JavaScript grid layout library. It works by placing
elements in optimal position based on available vertical space, sort
of like a mason fitting stones in a wall. You’ve probably seen it in
use all over the Internet.

This is untested but something like this should work after your code...
The idea is to continuously add 1pixel to the top margin of the problematic div until the difference between the two divs is 20px
while(position['div1'] - position['div2'] <20){
$('#div2').animate({marginTop: '+=1px'}, 0);​​​​​​​​​​​​​​​​​
}
If you want to show them directly in line as in your picture, it's even easier:
var diff = position['div1'] - position['div2']
if(diff < 20){
$('#div2').animate({marginTop: '+=' + diff + 'px'}, 0);​​​​​​​​​​​​​​​​​
}

Related

Pure CSS parallaxing (not fixed) background for single row in layout

I'm wondering if it's possible to use only CSS to create a parallax scrolling background that meets the following specifications.
It works on an element that sits inside an otherwise static layout (i.e. my whole page layout isn't a group of parallaxing items)
The background isn't entirely fixed in place; it moves, just not as fast as the rest of the page.
I've looked up tons of tutorials for parallaxing backgrounds, and have found some seemingly great tutorials, but they all have one of the following problems.
They rely on the whole page being a parallax group so that you're actually scrolling over a container via an "overflow: auto" specification
The background is totally fixed in place
they use JavaScript.
Sooo, I can accomplish what I want with JavaScript fairly easily. Here's a full working example on JSFiddle that you can try out.
CSS
.parallax-row {
background-image: url(http://lorempixel.com/output/nature-q-c-781-324-3.jpg);
background-size: auto 150%;
}
JavaScript
/**
* Update the parallaxing background img to partially scroll
*/
jQuery(document).ready(function($) {
$(window).on('scroll', function() {
$('.parallax-row').each(function(index, el) {
var $el = $(el);
var fromTop = $el.offset().top + ($el.outerHeight() / 2) - $(window).scrollTop();
var windowHeight = $(window).height();
var percent = (fromTop * 100 / windowHeight);
$el.css('background-position', '0 ' + percent + '%');
});
});
});
Is it possible to accomplish that same effect with just CSS?

Bootstrap affix navbar for single page with scrollspy and page anchors

This is for a single page, with a navbar that links to local anchors only.
The navbar comes after a header, but sticks to top when scrolling down.
You can see how it works on github pages
But I've got two offset problems with link/anchors:
as long as you don't scroll, the anchors are offset and masked by the navbar.
once the navbar is affixed, the following links work as intended but not the first one.
A body margin breaks the layout as it prevents the header from beginning right at the top:
body {
margin-top: 65px;
}
I've tried without success to play with margin/padding for the sections:
section {
padding-top: 65px;
margin-top: -65px;
}
Here are the html and css
Any idea how to fix that?
Can it be solved with pure css?
Or do I need some js fix to account for the affix?
I think your problem has only to do with the affix. I found a problem in 3 situations:
no scroll and clicking a link
click the first link
scoll, click the first link and click an other link.
In this three situation you click from an position where you affix is not applied to a position where your affix has been applied.
What happens your click scrolls the target anchor to the top of the page and applies the affix (set navbar's position to fixed) after this. Result the navbar overlaps the content.
I don't think you could fix this with css only. I think your solution of adding a margin / padding to the section will be right, but you will have to apply the margin after the affix.
I tried something like:
var tmp = $.fn.affix.Constructor.prototype.checkPosition;
var i = 0;
var correct = false
$.fn.affix.Constructor.prototype.checkPosition = function () {
$('#content').css('margin-top','0');
tmp.call(this);
if(i%2!=0 && $(window).scrollTop()<443){correct=true}
if(i%2==0 && correct){$('#content').css('margin-top','83px').trigger('create'); correct=false}
i++;
}
This feels to complex and also only seems to work on firefox now.
update
I think i could fix your problem by overwritting the complete affix checkPosition function:
$.fn.affix.Constructor.prototype.checkPosition = function ()
{
if (!this.$element.is(':visible')) return
var scrollHeight = $(document).height()
var scrollTop = this.$window.scrollTop()
var position = this.$element.offset()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
if(scrollTop==378)
{
this.$window.scrollTop('463');
scrollTop==463;
}
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top()
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()
var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false :
offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false
console.log(scrollTop + ':' + offsetTop);
if(scrollTop > offsetTop) {$('#content').css('margin-top','83px'); console.log('margin') }
else{$('#content').css('margin-top','0');}
if (this.affixed === affix) return
if (this.unpin) this.$element.css('top', '')
this.affixed = affix
this.unpin = affix == 'bottom' ? position.top - scrollTop : null
this.$element.removeClass('affix affix-top affix-bottom').addClass('affix' + (affix ? '-' + affix : ''))
if (affix == 'bottom') {
this.$element.offset({ top: document.body.offsetHeight - offsetBottom - this.$element.height() })
}
}
Some values are hard coded (now) so this function only will work for your example on github pages.
Demo: http://bootply.com/81336
On github pages you use "old" versions of jQuery and Bootstrap. You don't need to set an offset for the scrollspy. You don't have to call $('#navbar').scrollspy(); also cause you already set the scrollspy with data attributes.
See also: https://github.com/twbs/bootstrap/issues/10670
remove this hardcode values
When clicking an internal link (start with #{id}) the anchor with id={id} will be scrolled to the top of the viewport.
In this case there will be a fixed navbar (affix) so the anchor should scroll to the top minus the height of the navbar.
The height of the navbar will be 85px (63 pixels of the brand image + 2 pixels of the border + the margin-bottom of 20 px of the .navbarheader)
This value will be used here:
if(scrollTop > offsetTop) {$('#content').css('margin-top','83px'); console.log('margin') }
else{$('#content').css('margin-top','0');}
I have used 83 (may look better?).
So the 83 can be replaced with: var navbarheight = $('#nav').innerHeight()
Then we have these:
if(scrollTop==378)
{
this.$window.scrollTop('463');
scrollTop==463;//typo?? make no sense
}
The (first) link scrolls the anchor to the top where the affix is not
applied yet (below data-offset-top="443") the height of your fixed
navbar is not used in calculacting so this point will be 443 - 85
(navbarheight) = 378. This code could be replace with.
if(scrollTop==(443-navbarheight))
{
this.$window.scrollTop(scrollTop+navbarheight);
}
Note 443 now still will be hardcoded. It is also hardcoded in your
html with affix-top.
Watch out Replacing the values with the above won't work. The
situation between (af)fixed and not will change for every scroll
action. The part if(scrollTop==378) is a trick not a solution. It
solves the situation for scrollheight < data-offset-top. We could not
apply the whole range, case in that case the user can't never scroll
back to the top (this.$window.scrollTop scrolls him back again and again).
Also the calculation of navbarheight will be tricky. When the navbar
is fixed $('#nav').innerHeight() / height will return 85 (including
the margin). In the absolute position this will be 65.

css inline-block div positioning

I'm trying to fix a positing issue in a responsive design.
I have a container div, containing 4 (but it could be more or less) divs that are displayed as inline-block. I would like to know how to control the number of divs per line when the page is resized (with CSS, if it's possible). For example, when 4 containees no longer fits in the container, the last one is moved to second line. I would like in that case to have 2 containees in the first line and 2 containees in the second line. I dont know how to do that. Your help would be welcomed!
EDIT:
it could also be 6 containees, in the case the layout would be:
- 1 line of 6 blocks if it fits
- 2 lines of 3 blocks
- 3 lines of 2 blocks
- 6 lines of one
the number of containees is variable. I just want to have the same number of containees per line
the html:
<div class="container">
<div class="containee"></div>
<div class="containee"></div>
<div class="containee"></div>
<div class="containee"></div>
</div>
the css:
.containee {
width:200px;
height:200px;
display:inline-block;
background-color:tomato
}
the example can be seen here : http://cssdesk.com/uGLbq
(PS : I tried to find the solution searching the web but I dont really know the good keywords related with this topic)
You can't with CSS (AFAIK).
You can do "the math" dynamically with Javascript in real time.
In your case,
you known the width of one block (in that moment),
you can easily get the window width (in that moment),
you know the number of your block (in that moment);
Simply apply ( (1) the first time you open the page, and (2) every time the number of blocks changes, or (3) the resolution changes) the algorithm in the following code:
// EXAMPLE OF INPUT
var windowWidth = 1400; // read it...
var blockWidth = 200; // read it or use const...
var numberOfBlocks = 10; // read it...
// Calculate the maximum number of blocks per row
var maxBlocksPerRow;
for (var i=0; i < numberOfBlocks; i++) {
if ( (blockWidth * (i + 1)) > windowWidth){
maxBlocksPerRow = i;
break;
}
}
// Check the highest 0 module combination while iterating backwards
var magicNumberForMatchingBlocks = 1; // if not found, it will be 1.
for (var i = maxBlocksPerRow; i > 0 ; i--) {
if ( (numberOfBlocks % i) == 0){
magicNumberForMatchingBlocks = i;
break;
}
}
alert("With " + numberOfBlocks + " blocks, each one wide " +
blockWidth + " pixels, and a window wide " + windowWidth + " pixels,
the number of blocks per row for having always
the same number of block in any row is: " + magicNumberForMatchingBlocks);
Then use that number to populate or re-arrange the elements with Javascript or better with some Javascript library like jQuery.
html:
<div class="container">
<div class="grouped">
<div class="containee"></div>
<div class="containee"></div>
</div>
<div class="grouped">
<div class="containee"></div>
<div class="containee"></div>
</div>
</div>
css:
.containee {
width:200px;
height:200px;
display:inline-block;
background-color:tomato
}
.grouped {
float:left;
}
Try this:
.container
{
min-width: 410px;
}
Give the .containee a float:left; if the page fits for 4, they will be positioned right beside each other, else, you'll have another line of divs. You can give it as well a margin-top:5px; in case you got another line, the divs of the second line won't be glued to the divs of the first line. Note that with this approach, its not obliged to have equal number of .containee in each line, if you have 4, then you re-size, you'll have 3 - 1, then 2 - 2...etc..

HTML & CSS How to prevent a div from extending greater the height of the window?

How can I prevent a div which contains a long list of items from expanding the page height. I want the div to take up the entire screen but no more so that it doesn't push the footer down.
Set an specific height for the div container, and also set overflow-y with auto in order to show the scroll bar only when the content of the div is larger than the height set in the container. Like this:
.container {
height: 500px;
overflow-y:auto;
}
Without js, it is not possible because your page can be viewed in different resolution. Different resolutions means different height. Matter of fact, you may want that behaviour when user resizes the browser window as well, am I right? So first, find out the height of the browser, subtract the height of the footer from it, and set this height to your container, which I believe you want to make scroll able on yaxis. That will solve the problem. All these tasks are pretty simple and you can do it by little googling.
Use JavaScript/jQuery for this:
jQuery Solution:
<div id="content-div">some content here</div>
$(document).ready(function() {
var height = $(document).height();
height = height - (your footer height);
$("#content-div").css({ 'max-height' : height.toString() });
});
Standard JavaScript solution:
<div id="content-div">some content here</div>
function myfunction () {
document.getElementById('content-div').style.height = getDocHeight() + 'px';
}
window.onload = myfunction();
document.getElementById('content-div').style.height = getDocHeight() + 'px';
function getDocHeight() {
var D = document;
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
}
Also, change CSS to:
#content-div { background-color:#1d1d1d; color:#eee; overflow-y: scroll; }

text div with bookmark-like bar

I wrote jsfiddle example for better explanation, so, how to make red bars fill the whole height of .frame? And may be there are any absolutely different better way to make things like this?
Positioned elements are no longer part of the layout, so they have no idea what the dimensions of the parent element are. You need to use JavaScript to do this.
I solve it myself. JSfiddle demo.
var move_bookmark = function(){
var sh = parseInt($(this).css('height').replace('px',''));
var ph = parseInt($(this).parent().css('height').replace('px',''));
if (sh%2==0)//this is for solving [this problem] -
//http://math.stackexchange.com/questions/183018/pixel-rectangle-precise-rotating
{
if(ph%2!=0)
{
ph++;
$(this).parent().css('height',ph+'px');
}
}
else
{
if(ph%2==0)
{
ph++;
$(this).parent().css('height',ph+'px');
}
}
$(this).css('width',ph+'px');
var sw = ph;
var offset = parseInt(ph-sw/2-sh/2)+'px'
console.log(sw+"/"+sh);
$(this).css('top',offset);
$(this).css('left',-sw/2+sh/2+'px');
$(this).parent().css('padding','0px 0px 0px '+sh+'px');
}
$('.bookmark').each(move_bookmark);

Resources