Align content vertically JavaScript - javascript

Hy,
Basically what I want to achieve is to align some content vertically, in my case name & job.
The issue here is, when resizing the window, I want the content to stay in the middle.
I found a small script but I cannot get it to work, still learning the basics of JS.
My markup is the following:
Navigation
Vertically content
Footer (position: absolute; bottom: 0;) // is aligned to bottom.
I created a JSFiddle (http://jsfiddle.net/marianstroiu/khm52p0a/1/), so can you see what I'm talking about.
function getWindowHeight() {
var windowHeight = 0;
if (typeof(window.innerHeight) == 'number') {
windowHeight = window.innerHeight;
}
else {
if (document.documentElement && document.documentElement.clientHeight) {
windowHeight = document.documentElement.clientHeight;
}
else {
if (document.body && document.body.clientHeight) {
windowHeight = document.body.clientHeight;
}
}
}
return windowHeight;
}
function setContent() {
if (document.getElementById) {
var windowHeight = getWindowHeight();
if (windowHeight > 0) {
var contentElement = document.getElementById('v-content');
var contentHeight = contentElement.offsetHeight;
if (windowHeight - contentHeight > 0) {
contentElement.style.position = 'relative';
contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
}
else {
contentElement.style.position = 'static';
}
}
}
}
window.onload = function() {
setContent();
}
window.onresize = function() {
setContent();
}
Thank you!

You are using bootstrap sticky-footer template that add bottom margin and footer to the body element so you should substract 2 * 60 pixel from window height. Here is modified jsfiddle

Related

If window width doesn't work on resize

I've created a function that has to run only if the window is wider than 769px. It works when the page loads, but not on resize...
It looks like this:
$(window).on('load resize', function () {
if ($(window).width() >= 769) {
...funcion...
}
});
EDITED:
Full code below
$(window).on('load resize', function () {
if ($(window).width() >= 769) {
var $element = $('#cont_quote');
var $follow = $element.find('.img_quote');
var followHeight = $element.find('.img_quote').outerHeight();
var height = $element.outerHeight() - 300;
var window_height = $(window).height();
$(window).scroll(function () {
var pos = $(window).scrollTop();
var top = $element.offset().top;
// Check if element is above or totally below viewport
if (top + height - followHeight < pos || top > pos + window_height) {
return;
}
var offset = parseInt($(window).scrollTop() - top);
if (offset > 0) {
$follow.css('transform', 'translateY('+ offset +'px)');
}
})
}
});
HTML:
<section id="cont_quote">
<article class="cont_q">
Lorem ipsum
<img class="img_quote" src="img">
</article>
</section>
Try something like this:
$(document).ready(function(){
$(window).resize(function(){
if ($(window).width() >= 769) {
...funcion...
}
}
}
You can change on ready or on load, depending on what you need, but the the function should trigger on window resize.
I think you can try this solution this is just javaScript
var onWindowResize = function(e) {
width = e.target.outerWidth;
//uncomment if need height = e.target.outerHeight;
if(width >= 769) {
//remove alert just added for debug
alert("if");
}
else{
//remove alert
alert("else");
}
}
window.addEventListener("resize", onWindowResize);

Get the element which is the most visible on the screen

I would like to get the one element which is the most visible on the screen (takes up the most space). I have added an example picture below to understand my question a bit more.
The two black borders are the sides of a screen. As you can see, the green box (div2) is the most visible on the screen - I would like to know how I can get that element. The most visible element should not have to be fully visible.
I have done a quick (it wasn't THAT quick) seach but to no avail, if I have missed it - my apologies.
TLDR:
Inspired by this question and the necessity for similar functionality in my own projects, I've written a module/jQuery plugin based on the code below. If you're not interested in the 'how', just download that or install with your favourite package manager.
Original Answer:
The answer provided by exabyssus works well in most cases, apart from when neither of an element's top or bottom is visible e.g when the element height is greater than the window height.
Here's an updated version which takes that scenario into account and uses getBoundingClientRect which is supported right the way down to IE8:
// Usage: var $element = getMostVisible($('.elements' ));
function getMostVisible($elements) {
var element,
viewportHeight = $(window).height(),
max = 0;
$elements.each(function() {
var visiblePx = getVisibleHeightPx($(this), viewportHeight);
if (visiblePx > max) {
max = visiblePx;
element = this;
}
});
return $elements.filter(element);
}
function getVisibleHeightPx($element, viewportHeight) {
var rect = $element.get(0).getBoundingClientRect(),
height = rect.bottom - rect.top,
visible = {
top: rect.top >= 0 && rect.top < viewportHeight,
bottom: rect.bottom > 0 && rect.bottom < viewportHeight
},
visiblePx = 0;
if (visible.top && visible.bottom) {
// Whole element is visible
visiblePx = height;
} else if (visible.top) {
visiblePx = viewportHeight - rect.top;
} else if (visible.bottom) {
visiblePx = rect.bottom;
} else if (height > viewportHeight && rect.top < 0) {
var absTop = Math.abs(rect.top);
if (absTop < height) {
// Part of the element is visible
visiblePx = height - absTop;
}
}
return visiblePx;
}
This returns the most visible element based on pixels rather than as a percentage of the height of the element, which was ideal for my use-case. It could easily be modified to return a percentage if desired.
You could also use this as a jQuery plugin so you can get the most visible element with $('.elements').mostVisible() rather than passing the elements to the function. To do that, you'd just need to include this with the two functions above:
$.fn.mostVisible = function() {
return getMostVisible(this);
};
With that in place you can chain your method calls rather than having to save the element into a variable:
$('.elements').mostVisible().addClass('most-visible').html('I am most visible!');
Here's all of that wrapped up in a little demo you can try out right here on SO:
(function($) {
'use strict';
$(function() {
$(window).on('scroll', function() {
$('.the-divs div').html('').removeClass('most-visible').mostVisible().addClass('most-visible').html('I am most visible!');
});
});
function getMostVisible($elements) {
var element,
viewportHeight = $(window).height(),
max = 0;
$elements.each(function() {
var visiblePx = getVisibleHeightPx($(this), viewportHeight);
if (visiblePx > max) {
max = visiblePx;
element = this;
}
});
return $elements.filter(element);
}
function getVisibleHeightPx($element, viewportHeight) {
var rect = $element.get(0).getBoundingClientRect(),
height = rect.bottom - rect.top,
visible = {
top: rect.top >= 0 && rect.top < viewportHeight,
bottom: rect.bottom > 0 && rect.bottom < viewportHeight
},
visiblePx = 0;
if (visible.top && visible.bottom) {
// Whole element is visible
visiblePx = height;
} else if (visible.top) {
visiblePx = viewportHeight - rect.top;
} else if (visible.bottom) {
visiblePx = rect.bottom;
} else if (height > viewportHeight && rect.top < 0) {
var absTop = Math.abs(rect.top);
if (absTop < height) {
// Part of the element is visible
visiblePx = height - absTop;
}
}
return visiblePx;
}
$.fn.mostVisible = function() {
return getMostVisible(this);
}
})(jQuery);
.top {
height: 900px;
background-color: #999
}
.middle {
height: 200px;
background-color: #eee
}
.bottom {
height: 600px;
background-color: #666
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="the-divs">
<div class="top"></div>
<div class="middle"></div>
<div class="bottom"></div>
</div>
Yes, this question is too broad. But I was interested on solving it.
Here is crude example on how to accomplish it.
I tried to explain what's going on with comments. It surely can be done better, but I hope it helps.
// init on page ready
$(function() {
// check on each scroll event
$(window).scroll(function(){
// elements to be tested
var _elements = $('.ele');
// get most visible element (result)
var ele = findMostVisible(_elements);
});
});
function findMostVisible(_elements) {
// find window top and bottom position.
var wtop = $(window).scrollTop();
var wbottom = wtop + $(window).height();
var max = 0; // use to store value for testing
var maxEle = false; // use to store most visible element
// find percentage visible of each element
_elements.each(function(){
// get top and bottom position of the current element
var top = $(this).offset().top;
var bottom = top + $(this).height();
// get percentage of the current element
var cur = eleVisible(top, bottom, wtop, wbottom);
// if current element is more visible than previous, change maxEle and test value, max
if(cur > max) {
max = cur;
maxEle = $(this);
}
});
return maxEle;
}
// find visible percentage
function eleVisible(top, bottom, wtop, wbottom) {
var wheight = wbottom - wtop;
// both bottom and top is vissible, so 100%
if(top > wtop && top < wbottom && bottom > wtop && bottom < wbottom)
{
return 100;
}
// only top is visible
if(top > wtop && top < wbottom)
{
return 100 + (wtop - top) / wheight * 100;
}
// only bottom is visible
if(bottom > wtop && bottom < wbottom)
{
return 100 + (bottom - wbottom) / wheight * 100;
}
// element is not visible
return 0;
}
Working example - https://jsfiddle.net/exabyssus/6o30sL24/
<style>
.block{
padding: 20px;
border:2px solid #000;
height: 200px;
overflow:hidden;
}
.green{
border: 1px solid green;
height: 150px;
margin:20px 0px;
}
.red{
border: 1px solid red;
height: 100px;
}
</style>
<div class="block">
<div class="example green"></div>
<div class="example red"></div>
</div>
var divs = $('.example');
var obj = {};
var heights = [];
$.each(divs,function (key, val)
{
heights.push($(val).outerHeight());
obj[$(val).outerHeight()] = $(val);
});
var max = Math.max.apply(null, heights);
console.log(obj[max]);

Iframe height definition in IE 7

I have a problem with resizing iframe content in IE7.
I have an external iframe
<IFRAME id=fl_game src="my_iframe_page" frameBorder=0 allowTransparency scrolling=no></IFRAME>
with width=100%, height=93%
and add my page into it. Here is a page body
<div id="container">
<div id="game-box">
<div id="flashcontent">
</div>
</div>
</div>
<script type="text/javascript">
swfobject.embedSWF("<%=application.getContextPath()%>/flash/<%= request.getParameter(PARAM_GAME) %>/game.swf", "flashcontent", gameWidth, gameHeight, "10.1", "/flash/expressInstall.swf", flashvars, params);
</script>
On my page I add resize events.
if (window.addEventListener) {
window.addEventListener("load", resizeGame, false);
window.addEventListener("resize", resizeGame, false);
} else if (window.attachEvent) {
window.attachEvent("onload", resizeGame);
window.attachEvent("onresize", resizeGame);
} else {
window.onload = function() {resizeGame();};
window.onresize = function() {resizeGame();}
}
Here is my resizeGame function
function resizeGame(isIEResize) {
var flash = document.getElementById('flashcontent');
var screen = screenSize();
var width = screen.width;
var height = screen.height;
var left = 0;
var top = 0;
if (height * 1.5 > width) {
height = width / 1.5
} else {
width = height * 1.5;
}
flash.width = width;
flash.height = height;
document.getElementById('flashcontent').style.width = width + 'px';
document.getElementById('flashcontent').style.height = height + 'px';
document.getElementById('flashcontent').style.top = '50%';
document.getElementById('flashcontent').style.left = '50%';
if (width < screen.width) {
left = (screen.width - width) / 2 + left;
}
if (height < screen.height) {
top = (screen.height - height) / 2;
}
document.getElementById('game-box').style.top = top + 'px';
document.getElementById('game-box').style.left = left + 'px';
}
function screenSize() {
var w, h;
w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
return {width:w, height:h};
}
And here is a question:
In IE7 function screenSize() gives me wrong height on load. Under other browsers and IE>7 function screenSize() gives me correct height. That's why I can't resize my content properly.
And when I explicitly resize a window, function screenSize() starts to give correct height.
Here some screens before explicit resizing and after it.
screenSize() gives strange height ONLY in IE7.
I am ready to add any extra information to find a reason of this situation.
I hope someone can help me to find out how to define iframe height in IE7. Any help will be useful.

calculate and set the height for some div (initial settings). When the height of the browser window is changed --> change the height for div

I need calculate and set the height for some div (initial settings). When the height of the browser window is changed --> change the height for div.
How will be better to rewrite this code (I want do initial settings once and change it when window resize):
$(document).ready(function () {
var height = document.documentElement.clientHeight - 500;
if (height < 135) {
height = 135;
}
document.getElementById('left_space').style.height = height + 'px';
$(window).resize(function () {
var height = document.documentElement.clientHeight - 500;
if (height < 135)
{
height = 135;
}
document.getElementById('left_space').style.height = height + 'px';
});
});
If you are purely looking to tidy up the code, it could look something like this:
$(document).ready(function () {
var resizeIt = function() {
var height = Math.max(document.documentElement.clientHeight - 500, 135);
$('#left_space').css('height', height + 'px');
};
resizeIt();
$(window).resize(function () {
resizeIt();
});
});
Here I have pulled out the lines of code that set the height into their own function, so the code is not duplicated. Then I took advantage of some of the shorter syntax you can use in jQuery for finding and changing styles of elements.
is that what you are looking for?
api.jquery.com
jQuery(document).ready(function () {
$(window).resize(function() {
var height = document.documentElement.clientHeight - 500;
if (height < 135) {
height = 135;
}
document.getElementById('left_space').style.height = height + 'px';
jQuery(window).resize(function () {
var height = document.documentElement.clientHeight - 500;
if (height < 135)
{
height = 135;
}
document.getElementById('left_space').style.height = height + 'px';
});
});
});
I think jQuery(window).resize one would be good

"Zooming" elements on a page while keeping the centre of enlargement in the centre of the window

I'm trying to work out how to enlarge all elements on a page, but keep the centre of enlargement in the centre of the window.
On this page, once the image reaches the top or the left side of the window the centre of enlargement changes. It also changes when you move the image. (exactly what you would expect)
I'm thinking I'd need to take a completely different approach to achieve what I want. But I'm not sure what that approach is..
Any ideas?
Well, here's my take.
Only thing is that I ditched the containers you were using. Is that cheating? Seems like they were only there to get the image centered. No need.
This works as expected with no side effects.
Here's a working demo you can test:
http://jsfiddle.net/YFPRB/1/
(You need to click on the pane with the baboon first.)
HTML
<body>
<img src="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png" />
</body>
CSS
html, body {
width: 100%;
height: 100%;
overflow: hidden;
}​
jQuery
EDIT: Thanks to #stagas for the reminder to clean up redundancies.
var $img = $('img'); // Cache the image. Better for performance.
$img.draggable();
$img.css({left: ($('body').width() / 2) - ($img.width() / 2)})
.css({top: ($('body').height() / 2) - ($img.height() / 2)})
$(document).keydown(function(event) {
if (event.keyCode == 38) {
var adjustment = 1.25;
} else if (event.keyCode == 40) {
var adjustment = 0.8;
} else {
return;
}
var offset = $img.offset();
var width = $img.width();
var height = $img.height();
var newWidth = width * adjustment;
var newHeight = height * adjustment;
var diffWidth = newWidth - width;
var diffHeight = newHeight - height;
var hcenter = $('body').width() / 2;
var vcenter = $('body').height() / 2;
var leftPercent = (hcenter - offset.left) / width;
var topPercent = (vcenter - offset.top) / height;
$img.offset({top: offset.top - (diffHeight * topPercent), left: offset.left - (diffWidth * leftPercent)});
$img.width(newWidth).height(newHeight);
});​
This is what I came up, it works as you say except the image will always go to the center after zooming in or out:
$('document').ready(function() {
zoomimg=$('#zoomimg'); // we store this in a variable since we don't need to traverse the DOM every time -- this is faster
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height(); // this is to work with Opera
zoomimg.css({'position': 'absolute', 'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)}).draggable();
$(document).keydown(function(event) {
event = event || window.event;
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height(); // this is to work with Opera
if (event.keyCode == 38) {
width = zoomimg.width();
height = zoomimg.height();
zoomimg.width(width*1.2).height(height*1.2);
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
zoomimg.css({'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)});
} else if (event.keyCode == 40) {
width = zoomimg.width();
height = zoomimg.height();
zoomimg.width(width*0.8).height(height*0.8);
var viewportWidth = $(window).width();
var viewportHeight = window.innerHeight ? window.innerHeight : $(window).height();
zoomimg.css({'left': (viewportWidth/2)-(zoomimg.width()/2), 'top' : (viewportHeight/2)-(zoomimg.height()/2)});
} else {
return
}
});
});
You should put an ID 'zoomimg' on the tag for it to work, and overflow:hidden on the #container . Also ditch that display:table and display:table-cell they're useless now that we center with Javascript. Also, pressing the down arrow key will cause the container to scroll down, so you should use other keys, as the arrows are reserved by the browser for scrolling the viewport.

Categories

Resources