Make javascript-snippet affect 3 divs instead of 1 - javascript

I have this very usefull little piece of javascript that centers mig div. By i would like to make it apply to 3 divs on the same site, without repeating the same piece of code 3 times.
Any ideas on how to do it?
Putting all 3 divs into 1 divs that takes care of it, is not and option.
<script type="text/javascript">
<!--
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('outer');
var contentHeight = contentElement.offsetHeight;
if (windowHeight < 570) {
contentElement.style.position = 'relative';
contentElement.style.top = '30px';
}
else 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();
}
//-->
</script>
Regards Troels

You don't need to check if document.getElementById exists. It has been supported since the Roman Empire.
Pass the id or the actual element that has to be centered to your function. That removes the dependency on a fixed element (#outer) in your case and makes it more flexible. Also try to name your functions to be indicative of what they are actually doing. setContent is a very generic name and doesn't indicate the centering aspect anywhere.
function centerElementWithId(id) {
..
var contentElement = document.getElementById(id);
..
}
Then call it thrice,
centerElementWithId('outer')
centerElementWithId('secondDiv')
centerElementWithId('thirdDiv');

Related

How do I make the script work with percentage?

I have this pop up window being centered by javascript using px. I need the box to be responsive so how can I adjust the script to calculate for percentages and not px. Is it possible? This current code allows me to produce an automatic pop up but it also has script that centers the pop using px. This is not responsive.
function toggle(div_id) {
var el = document.getElementById(div_id);
if ( el.style.display == 'none' ) { el.style.display = 'block';}
else {el.style.display = 'none';}
}
function blanket_size(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportheight = window.innerHeight;
} else {
viewportheight = document.documentElement.clientHeight;
}
if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
blanket_height = viewportheight;
} else {
if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
blanket_height = document.body.parentNode.clientHeight;
} else {
blanket_height = document.body.parentNode.scrollHeight;
}
}
var blanket = document.getElementById('blanket');
blanket.style.height = blanket_height + 'px';
var popUpDiv = document.getElementById(popUpDivVar);
popUpDiv_height=blanket_height/2-187.5;//200 is half popup's height
popUpDiv.style.top = popUpDiv_height + 'px';
}
function window_pos(popUpDivVar) {
if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerHeight;
} else {
viewportwidth = document.documentElement.clientHeight;
}
if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
window_width = viewportwidth;
} else {
if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
window_width = document.body.parentNode.clientWidth;
} else {
window_width = document.body.parentNode.scrollWidth;
}
}
var popUpDiv = document.getElementById(popUpDivVar);
window_width=window_width/2-250;//200 is half popup's width
popUpDiv.style.left = window_width + 'px';
}
function popup(windowname) {
blanket_size(windowname);
window_pos(windowname);
toggle('blanket');
toggle(windowname);
}
This seems like an awful lot of javascript to display a popup dialog. You can accomplish this functionality with CSS/HTML alone, although many solutions will use HTML/CSS for the layout, and some javascript to show/hide the dialog.
I dont like to use javascript at all for the actual layout of the webpage, such as positioning elements. CSS was designed specifically for positioning and styling web elements, and it is generally more efficient than JS.
You may want to check out some of the many guides available online for HTML/CSS Modal Dialogs. These are done with minimal javascript.
Check out this one for starters
http://www.webdesignerdepot.com/2012/10/creating-a-modal-window-with-html5-and-css3/
Good luck
You really don't need JavaScript to center something - for that, we have CSS! To center something horizontally, simply use the following CSS on the element
margin: auto;
To center something vertically, you can use something like
top: 50%;
transform: translateY(-50%);
position:relative;

Free-Scrolling Sticky Sidebar Without jQuery

I'm trying to achieve what is outlined in this Stack Overflow question, without jQuery dependency: stackoverflow.com/questions/18358816/sticky-sidebar-stick-to-bottom-when-scrolling-down-top-when-scrolling-up
But I didn't want to hijack that question.
Basically, I want the content in the sidebar to be independently scrollable but fixed when the viewport reaches either end of the sidebars contents on scroll.
My main stumbling block appears to not being able to calculate the elementTop variable when the sidebar is absolutely positioned and between the top and bottom of the container which I have set to be full height.
Full code below:
var StickySidebar = function(eventie) {
var container, containerTop, containerHeight, // container
element, elementTop, elementHeight, elStyle, // element
viewportTop = -1, viewportHeight, documentTop, // viewport
lastViewportTop, scrollingDown, top = false , bottom = false,// sticky vars
scroll = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame ||
function(callback){ window.setTimeout(callback, 1000/60); },
options = {
container : document.querySelector('.sidebar-container'),
element : document.querySelector('.sidebar'),
sidebarClass : 'sidebar',
bottomOffset : -15,
topOffset: 90,
},
_updateValue = function() {
viewportHeight = window.innerHeight;
},
_offset = function(obj) {
var ol = ot = 0;
if (obj.offsetParent) {
do {
ol += obj.offsetLeft;
ot += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {
left: ol,
top: ot
};
},
init = function(){
if(options.element !== null) {
container = options.container;
containerTop = offset(container).top;
containerHeight = container.clientHeight;
element = options.element;
elementTop = offset(element).top;
elementHeight = options.element.clientHeight;
lastViewportTop = window.scrollY;
viewportHeight = window.innerHeight;
eventie.bind(document, "scroll", _loop);
eventie.bind(window, "resize", _updateValue);
}
},
_loop = function() {
if (viewportTop == window.pageYOffset) {
scroll(_loop);
return false;
} else viewportTop = window.pageYOffset;
_updateValue();
var viewportBottom, elementTooBig, topOffset;
elementTop = offset(element).top;
elementHeight = element.clientHeight;
containerHeight = container.clientHeight;
scrollingDown = viewportTop > lastViewportTop;
elementTooBig = elementHeight > viewportHeight;
console.log("elementTop : " + elementTop);
console.log("viewportTop : " + viewportTop);
if (scrollingDown) {
if (viewportTop + viewportHeight >= elementTop + elementHeight) {
element.setAttribute('style','position:fixed; bottom:30px;');
} else {
element.setAttribute('style','position:absolute; top:'+ elementTop +'px;'); // issue 1
}
if (viewportTop + viewportHeight > containerTop + containerHeight) {
element.setAttribute('style','position:absolute; bottom:0;');
}
} else {
if (viewportTop < containerTop - 60) {
element.removeAttribute('style');
return;
}
if (viewportTop <= elementTop) {
element.setAttribute('style','position:fixed; top:90px;');
} else {
element.setAttribute('style','position:absolute; top:'+ elementTop +'px;');
elementTop = viewportTop + elementTop;
}
}
lastViewportTop = viewportTop;
};
return {
init: init
};
}(eventie);
I've been trying to tackle this issue for a few weeks now, and it has been driving me insane. Any help would be greatly appreciated.
If you're just trying to achieve the desired result not necessarily creating that yourself - well, there are many JavaScript libraries that provide that.
For example, Stickyfill is actually a polyfill for position: sticky which is natively supported only in Firefox 41+ and Safari 8+. Here is the demo with all kinds of stickiness you can imagine :)
P.S. At first glance you might notice something about jQuery there, but it's pure JavaScript and just adds a jQuery extension.

Delay of Javascript based Tumblr width calculation

my Tumblr theme CSS width is changed by javascript code (according to the number of posts).
Theme is loaded with the standard width and after the number of posts is known, the new width is calculated by the following javascript function (to fit posts).
PROBLEM is the big delay of this calculation (it waits until content of posts is loaded)!
Is it possible to calculate and set width immediately based on number of posts and not to wait for posts content loading?
<script type="text/javascript">
function resizedivs() {
$ = function(id) { return document.getElementById(id); }
fschildren = $("fs_wrapper").childNodes;
postc = 0;
thedivs = new Array();
for(i = 0; i < fschildren.length; i++) {
if(fschildren[i].tagName == "DIV") {
thedivs[postc] = fschildren[i];
postc++;
}
}
newwidth = 0;
for(i = 0; i < thedivs.length; i++) {
if(newwidth <= document.body.clientWidth) {
newwidth = newwidth + (thedivs[i].clientWidth)+15;
}
if(newwidth >= document.body.clientWidth || newwidth >= 1300) { // 100 for padding minus 15 extra
newwidth = newwidth - (thedivs[i].clientWidth+15);
break;
}
}
$("fs_wrapper").style.width = newwidth-0+"px";
$("fs_wrapper").style.position = "relative";
$("fs_wrapper").style.left = "0px";
$("sec2").style.width = newwidth-0+"px";
$("sec2").style.position = "relative";
$("sec2").style.left = "0px";
$("sec3").style.width = newwidth-0+"px";
$("sec3").style.position = "relative";
$("sec3").style.left = "0px";
}
window.onresize = function() {
resizedivs();
}
window.onload = function() {
resizedivs();
}
</script>

Scroll if element is not visible

how to determine, using jquery, if the element is visible on the current page view. I'd like to add a comment functionality, which works like in facebook, where you only scroll to element if it's not currently visible. By visible, I mean that it is not in the current page view, but you can scroll to the element.
Live Demo
Basically you just check the position of the element to see if its within the windows viewport.
function checkIfInView(element){
var offset = element.offset().top - $(window).scrollTop();
if(offset > window.innerHeight){
// Not in view so scroll to it
$('html,body').animate({scrollTop: offset}, 1000);
return false;
}
return true;
}
Improving Loktar's answer, fixing the following:
Scroll up
Scroll to a display:none element (like hidden div's etc)
function scrollToView(element){
var offset = element.offset().top;
if(!element.is(":visible")) {
element.css({"visibility":"hidden"}).show();
var offset = element.offset().top;
element.css({"visibility":"", "display":""});
}
var visible_area_start = $(window).scrollTop();
var visible_area_end = visible_area_start + window.innerHeight;
if(offset < visible_area_start || offset > visible_area_end){
// Not in view so scroll to it
$('html,body').animate({scrollTop: offset - window.innerHeight/3}, 1000);
return false;
}
return true;
}
After trying all these solutions and many more besides, none of them satisfied my requirement for running old web portal software (10 years old) inside IE11 (in some compatibility mode). They all failed to correctly determine if the element was visible. However I found this solution. I hope it helps.
function scrollIntoViewIfOutOfView(el) {
var topOfPage = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
var heightOfPage = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var elY = 0;
var elH = 0;
if (document.layers) { // NS4
elY = el.y;
elH = el.height;
}
else {
for(var p=el; p&&p.tagName!='BODY'; p=p.offsetParent){
elY += p.offsetTop;
}
elH = el.offsetHeight;
}
if ((topOfPage + heightOfPage) < (elY + elH)) {
el.scrollIntoView(false);
}
else if (elY < topOfPage) {
el.scrollIntoView(true);
}
}
I made a slightly more generic version of digitalPBK's answer that minimally scrolls an element contained within a div or some other container (including the body). You can pass DOM elements or selectors to the function, as long as the element is somehow contained within the parent.
function scrollToView(element, parent) {
element = $(element);
parent = $(parent);
var offset = element.offset().top + parent.scrollTop();
var height = element.innerHeight();
var offset_end = offset + height;
if (!element.is(":visible")) {
element.css({"visibility":"hidden"}).show();
var offset = element.offset().top;
element.css({"visibility":"", "display":""});
}
var visible_area_start = parent.scrollTop();
var visible_area_end = visible_area_start + parent.innerHeight();
if (offset-height < visible_area_start) {
parent.animate({scrollTop: offset-height}, 600);
return false;
} else if (offset_end > visible_area_end) {
parent.animate({scrollTop: parent.scrollTop()+ offset_end - visible_area_end }, 600);
return false;
}
return true;
}
You can take a look at his awesome link from the jQuery Cookbook:
Determining Whether an Element Is Within the Viewport
Test if Element is contained in the Viewport
jQuery(document).ready(function() {
var viewportWidth = jQuery(window).width(),
viewportHeight = jQuery(window).height(),
documentScrollTop = jQuery(document).scrollTop(),
documentScrollLeft = jQuery(document).scrollLeft(),
$myElement = jQuery('#myElement'),
elementOffset = $myElement.offset(),
elementHeight = $myElement.height(),
elementWidth = $myElement.width(),
minTop = documentScrollTop,
maxTop = documentScrollTop + viewportHeight,
minLeft = documentScrollLeft,
maxLeft = documentScrollLeft + viewportWidth;
if (
(elementOffset.top > minTop && elementOffset.top + elementHeight < maxTop) &&
(elementOffset.left > minLeft && elementOffset.left + elementWidth < maxLeft)
) {
alert('entire element is visible');
} else {
alert('entire element is not visible');
}
});
Test how much of the element is visible
jQuery(document).ready(function() {
var viewportWidth = jQuery(window).width(),
viewportHeight = jQuery(window).height(),
documentScrollTop = jQuery(document).scrollTop(),
documentScrollLeft = jQuery(document).scrollLeft(),
$myElement = jQuery('#myElement'),
verticalVisible, horizontalVisible,
elementOffset = $myElement.offset(),
elementHeight = $myElement.height(),
elementWidth = $myElement.width(),
minTop = documentScrollTop,
maxTop = documentScrollTop + viewportHeight,
minLeft = documentScrollLeft,
maxLeft = documentScrollLeft + viewportWidth;
function scrollToPosition(position) {
jQuery('html,body').animate({
scrollTop : position.top,
scrollLeft : position.left
}, 300);
}
if (
((elementOffset.top > minTop && elementOffset.top < maxTop) ||
(elementOffset.top + elementHeight > minTop && elementOffset.top +
elementHeight < maxTop))
&& ((elementOffset.left > minLeft && elementOffset.left < maxLeft) ||
(elementOffset.left + elementWidth > minLeft && elementOffset.left +
elementWidth < maxLeft)))
{
alert('some portion of the element is visible');
if (elementOffset.top >= minTop && elementOffset.top + elementHeight
<= maxTop) {
verticalVisible = elementHeight;
} else if (elementOffset.top < minTop) {
verticalVisible = elementHeight - (minTop - elementOffset.top);
} else {
verticalVisible = maxTop - elementOffset.top;
}
if (elementOffset.left >= minLeft && elementOffset.left + elementWidth
<= maxLeft) {
horizontalVisible = elementWidth;
} else if (elementOffset.left < minLeft) {
horizontalVisible = elementWidth - (minLeft - elementOffset.left);
} else {
horizontalVisible = maxLeft - elementOffset.left;
}
var percentVerticalVisible = (verticalVisible / elementHeight) * 100;
var percentHorizontalVisible = (horizontalVisible / elementWidth) * 100;
if (percentVerticalVisible < 50 || percentHorizontalVisible < 50) {
alert('less than 50% of element visible; scrolling');
scrollToPosition(elementOffset);
} else {
alert('enough of the element is visible that there is no need to scroll');
}
} else {
// element is not visible; scroll to it
alert('element is not visible; scrolling');
scrollToPosition(elementOffset);
}
The following code helped me achieve the result
function scroll_to_element_if_not_inside_view(element){
if($(window).scrollTop() > element.offset().top){
$('html, body').animate( { scrollTop: element.offset().top }, {duration: 400 } );
}
}
Here is the solution I came up with, working both up and down and using only Vanilla Javascript, no jQuery.
function scrollToIfNotVisible(element) {
const rect = element.getBoundingClientRect();
// Eventually an offset corresponding to the height of a fixed navbar for example.
const offset = 70;
let scroll = false;
if (rect.top < offset) {
scroll = true;
}
if (rect.top > window.innerHeight) {
scroll = true;
}
if (scroll) {
window.scrollTo({
top: (window.scrollY + rect.top) - offset,
behavior: 'smooth'
})
}
}
There is a jQuery plugin which allows us to quickly check if a whole element (or also only part of it) is within the browsers visual viewport regardless of the window scroll position. You need to download it from its GitHub repository:
Suppose to have the following HTML and you want to alert when footer is visible:
<section id="container">
<aside id="sidebar">
<p>
Scroll up and down to alert the footer visibility by color:
</p>
<ul>
<li><span class="blue">Blue</span> = footer <u>not visible</u>;</li>
<li><span class="yellow">Yellow</span> = footer <u>visible</u>;</li>
</ul>
<span id="alert"></span>
</aside>
<section id="main_content"></section>
</section>
<footer id="page_footer"></footer>
So, add the plugin before the close of body tag:
<script type="text/javascript" src="js/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="js/jquery_visible/examples/js/jq.visible.js"></script>
After that you can use it in a simple way like this:
<script type="text/javascript">
jQuery( document ).ready(function ( $ ) {
if ($("footer#page_footer").visible(true, false, "both")) {
$("#main_content").css({"background-color":"#ffeb3b"});
$("span#alert").html("Footer visible");
} else {
$("#main_content").css({"background-color":"#4aafba"});
$("span#alert").html("Footer not visible");
}
$(window).scroll(function() {
if ($("footer#page_footer").visible(true, false, "both")) {
$("#main_content").css({"background-color":"#ffeb3b"});
$("span#alert").html("Footer visible");
} else {
$("#main_content").css({"background-color":"#4aafba"});
$("span#alert").html("Footer not visible");
}
});
});
</script>
Here a demo
No-JQuery version.
The particular case here is where the scroll container is the body (TBODY, table.body) of a TABLE (scrolling independently of THEAD). But it could be adapted to any situation, some simpler.
const row = table.body.children[ ... ];
...
const bottomOfRow = row.offsetHeight + row.offsetTop ;
// if the bottom of the row is in the viewport...
if( bottomOfRow - table.body.scrollTop < table.body.clientHeight ){
// ... if the top of the row is in the viewport
if( row.offsetTop - table.body.scrollTop > 0 ){
console.log( 'row is entirely visible' );
}
else if( row.offsetTop - table.body.scrollTop + row.offsetHeight > 0 ){
console.log( 'row is partly visible at top')
row.scrollIntoView();
}
else {
console.log( 'top of row out of view above viewport')
row.scrollIntoView();
}
}
else if( row.offsetTop - table.body.scrollTop < table.body.clientHeight ){
console.log( 'row is partly visible at bottom')
row.scrollIntoView();
}
else {
console.log( 'row is out of view beneath viewport')
row.scrollIntoView();
}
I think this is the complete answer. An elevator must be able to go both up and down ;)
function ensureVisible(elementId, top = 0 /* set to "top-nav" Height (if you have)*/) {
let elem = $('#elementId');
if (elem) {
let offset = elem.offset().top - $(window).scrollTop();
if (offset > window.innerHeight) { // Not in view
$('html,body').animate({ scrollTop: offset + top }, 1000);
} else if (offset < top) { // Should go to top
$('html,body').animate({ scrollTop: $(window).scrollTop() - (top - offset) }, 1000);
}
}
}

How to 'grow' an iFrame depending on the size of its contents?

I'm loading the iFrames dynamically and some pages are 'taller' than others. I'd like the iFrame to grow accordingly. Is it possible? If so, how?
Yes, it is possible by jquery.
Parent page code:
<iframe id='ifrm' />
Script on iframe page:
function alertSize() {
var myHeight = 0;
if (typeof (parent.window.innerWidth) == 'number') {
//Non-IE
myHeight = parent.window.innerHeight;
} else if (parent.document.documentElement
&& (parent.document.documentElement.clientWidth || parent.document.documentElement.clientHeight)) {
//IE 6+ in 'standards compliant mode'
myHeight = parent.document.documentElement.clientHeight;
} else if (parent.document.body && (parent.document.body.clientWidth || parent.document.body.clientHeight)) {
//IE 4 compatible
myHeight = parent.document.body.clientHeight;
}
//window.alert( 'Height = ' + myHeight );
return myHeight;
}
function AssignFrameHeight() {
var theFrame = $("#ifrm", parent.document.body);
var frameHeight1 = getIframeHeight('ifrm');
var frameHeight2 = $(document.body).height();
if ($(document.body)[0]) {
if ($(document.body)[0].bottomMargin)
frameHeight2 += Number($(document.body)[0].bottomMargin);
if ($(document.body)[0].topMargin)
frameHeight2 += Number($(document.body)[0].topMargin);
}
if (frameHeight1 > frameHeight2) {
theFrame.height(frameHeight1 - 20);
} else {
if ($.browser.msie)
theFrame.height(frameHeight2);
else
theFrame.height(frameHeight2 + 50);
}
}
function getIframeHeight(iframeName) {
//var iframeWin = window.frames[iframeName];
var iframeEl = parent.document.getElementById
? parent.document.getElementById(iframeName)
: parent.document.all
? parent.document.all[iframeName]
: null;
if (iframeEl) {
iframeEl.style.height = "auto"; // helps resize (for some) if new doc shorter than previous
//var docHt = getDocHeight(iframeWin.document);
// need to add to height to be sure it will all show
var h = alertSize();
//var new_h = (h - 148);
//iframeEl.style.height = h + "px";
return h;
//alertSize();
}
}
Reassign height after postback:
function pageLoad() { // MS AJAX - UpdatePanel
AssignFrameHeight();
}
$(document).ready(function() { // jQuery
AssignFrameHeight();
});
You might be able to do something like
document.getElementById('your-iframe').height=new_height;
But if you really need to have an iframe grow depending on the content then I suggest you try another html element as an iframe might not be what you need.
try using width:100%; height:100% and apply them on your iframe element

Categories

Resources