Javascript not responsive on resize - javascript

Newbie to Javascript here.
I'm trying to make a simple one-page site with 3 sections: the Title area, a Portfolio area, and a contact form. Each of these sections is anchor-linked, so when the link is clicked the page scrolls down to that section.
I've used javascript to ensure that each section will fill the screen, centered horizontally and vertically if space permits. However, these measurements won't update on window resize.
I can't pinpoint the issue, since my initial code, which controls the height of the header depending on the height of the viewport, did update on resize until I added in the new lines.
Here is the script:
<script type="text/javascript">//<![CDATA[
function resize()
{
var heights = window.innerHeight;
var header = document.getElementById('title').offsetHeight;
var logo = document.getElementById('logo').offsetHeight;
var portfolioHeight = document.getElementById('portfolio-buttons').offsetHeight;
var hireHeight = document.getElementById('hire-form').offsetHeight;
document.getElementById('header').style.height = heights - header - logo * 0.4 + "px";
document.getElementById('portfolio').style.padding = (heights - portfolioHeight) * 0.5 + "px 0";
document.getElementById('hire').style.padding = (heights - hireHeight) * 0.5 + 5 + "px 0";
}
resize();
window.onresize = function() {
resize();
};
//]]>
</script>
And here is the basic structure of the relevant HTML :
<div id="portfolio">
<div id="portfolio-buttons">
Content here
</div>
</div>
<div id="hire">
<div id="hire-form">
Content here
</div>
</div>
EDIT: To be extra clear, here are the lines that work as their own script:
<script type="text/javascript">//<![CDATA[
function resize()
{
var heights = window.innerHeight;
var header = document.getElementById('title').offsetHeight;
var logo = document.getElementById('logo').offsetHeight;
document.getElementById('header').style.height = heights - header - logo * 0.4 + "px";
}
resize();
window.onresize = function() {
resize();
};
//]]>
</script>
And here are those that work, but only update on refresh, not resize.
<script type="text/javascript">//<![CDATA[
function resize()
{
var heights = window.innerHeight;
var portfolioHeight = document.getElementById('portfolio-buttons').offsetHeight;
var hireHeight = document.getElementById('hire-form').offsetHeight;
document.getElementById('portfolio').style.padding = (heights - portfolioHeight) * 0.5 + "px 0";
document.getElementById('hire').style.padding = (heights - hireHeight) * 0.5 + 5 + "px 0";
}
resize();
window.onresize = function() {
resize();
};
//]]>
</script>

Try
window.onresize = function() {
resize();
return true;
};
If that doesn't work, try using window.addEventListener("resize",function(){...}) isntead. To support older versions of IE, you'll have to check if(window.addEventListener){/*standards*/window.addEventListener("resize",function(){...})}else{/*IE only*/ window.attachEvent("onresize",function(){...}

Related

Progress bar in a div

I have a progress bar on my body. When I click on a button a div appear, we can scoll on this div and I would liked to have also a progress bar for this one. I took the Jquery code of the progress bar
MY JSFIDDLE
window.onscroll = function() {
myFunction()
};
function myFunction() {
var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 100;
document.getElementById("myBar").style.height = scrolled + "%";
}
$('button').click(function() {
if ($(this).hasClass("clicked")) {
$(this).text("Open ↓");
} else {
$(this).text("Close ↑");
}
$('.blue-container').toggleClass('In');
$('body').toggleClass('hideOverflow');
$(this).toggleClass("clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="progress-container">
<div class="progress-bar" id="myBar"></div>
</div>
<button> Open ↓</button>
<div class='blue-container'>
<div class='blue'>
<p>Hello ! Scroll down. I would like to have a progress bar for this div, like the body.</p>
</div>
</div>
You need to create same progress setter function like you've set on window, except this one should use blue container scrollable element for scroll position measurement.
Remember that after your blue box is closed, you don't need setting progress from this box anymore, so you should unbind setter function ($scroller.off('scroll', progressSetter)). It will be bound again after next opening of blue box.
window.onscroll = function() {myFunction()};
function myFunction() {
var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrolled = (winScroll / height) * 100;
document.getElementById("myBar").style.height = scrolled + "%";
}
$('button').on('click', function() {
var $container = $('.blue-container'),
$scroller = $container.find('.blue'),
$btn = $(this),
$bar = $('#myBar'),
progressSetter = function () {
var height = $scroller[0].scrollHeight - $scroller.outerHeight();
$bar.css({
height: $scroller.scrollTop() / height * 100 + '%'
});
};
if ($btn.hasClass("clicked")) {
$btn.text("Open ↓");
$scroller.off('scroll', progressSetter)
} else {
$btn.text("Close ↑");
$scroller.on('scroll', progressSetter)
}
$container.toggleClass('In');
$('body').toggleClass('hideOverflow');
$btn.toggleClass("clicked");
});
https://jsfiddle.net/uo34ru7d/76/
As I can see, you used example code from tutorial. Try to figure out how this scrolling bound functions work (and event binding itself) and you will be able to create one function for both window and your blue container, make that your homework ;)

Centering div margin top and margin bottom

I'm trying to get margin-top and margin-bottom to center my <div>. This JavaScript, which I wrote, works. However, if the site is cached once, CTRL+F5 refresh causes the script to receive a wrong clientHeight. Refreshing second time, retrieves the correct clientHeight.
I've tried using window.load and this works. However, it is so slow that the <div> loads and after 2 seconds, it shifts to the middle.
<script type="text/javascript">
var height = $(window).height();
var clientHeight = document.getElementById('account-wall').clientHeight;
var calc_height = (height - clientHeight) / 2;
document.getElementById("account-wall").style.marginTop = calc_height + 'px';
document.getElementById("account-wall").style.marginBottom = calc_height + 'px';
</script>
<script type="text/javascript">
$(window).load(function() {
var height = $(window).height();
console.log(height);
var clientHeight = $('.account-wall').height();
console.log(clientHeight);
var calc_height = (height - clientHeight) / 2;
document.getElementById("account-wall").style.marginTop = calc_height + 'px';
document.getElementById("account-wall").style.marginBottom = calc_height + 'px';
});
</script>
Use a resize event since you need it to be centered even if the window.height changes. To make sure it is centered from the beggining use .resize() to trigger the event.
$(window).on('resize', function(event){
var height = $(window).height();
console.log(height);
var clientHeight = $('.account-wall').height();
console.log(clientHeight);
var calc_height = (height - clientHeight)/2;
document.getElementById("account-wall").style.marginTop = calc_height+'px';
document.getElementById("account-wall").style.marginBottom = calc_height+'px';
}).resize();

Element not staying within defined area in javascript

I wrote a basic program that moves a button inside a DIV element. The button is not staying within the area I had intended. On the HTML side I have code that defines the DIV with an id = "page". Here is the js code. Why is the button not staying within the DIV element?
var buttonState = document.getElementById("clickMe");
var maxWidth = document.getElementById("page");
var maxHeight = document.getElementById("page");
var pageWidth = maxWidth.clientWidth;
var pageHeight = maxHeight.clientHeight;
var screenWidth = 0;
var screenHeight = 0;
function moveButton() {
"use strict";
// Find max width and height of screen and set variables to random number within parameters
screenWidth = Math.floor(Math.random() * (pageWidth)) + 1;
screenHeight = Math.floor(Math.random() * (pageHeight)) + 1;
console.log(screenWidth);
console.log(screenHeight);
// Button position
buttonState.style.left = (screenWidth) + "px";
buttonState.style.top = (screenHeight) + "px";
// Button size
buttonState.style.width = buttonSize + "em";
buttonState.style.height = buttonSize + "em";
In your equations for screenWidth and screenHeight you need to take into account the size of the button.
The div is positioned based on the top left pixel so if you end up with Math.random() returning 1 or something very close to it, the button will fall out of the page unless you subtract the button sizes from the maxes.
var buttonWidthPx = buttonState.offsetWidth;
var buttonHeightPx = buttonState.offsetHeight;
screenWidth = Math.floor(Math.random() * (pageWidth - buttonWidthPx)) + 1;
screenHeight = Math.floor(Math.random() * (pageHeight - buttonHeightPx)) + 1;
Also make sure to set the positioning of the button to relative so it positions inside the div and not absolute to the document.
First thought, it is probably more of a css layout issue than javascript or html.
The first clue to this is
buttonState.style.left
buttonState.syyle.top
If you check the buttonState in Chrome DevTools you might find the layout to be: absolute and that would be one good reason why it does not layout as intended. Another would be if layout is set to static.
Here is a link that gives good depth of information on css layout settings: http://alistapart.com/article/css-positioning-101
The first thing I would try would be to open DevTools and deselect (remove) all the styles that buttonState has until you find the layout that is causing the problem.
I don't know the exact problem that you are facing because you didn't provide any HTML/CSS, but check out this fiddle for a working example.
<div id="page">
<button id="clickMe">Click Me</button>
</div>
<button id="move">Move Button</button>
#page {
width:300px;
height: 300px;
background-color: whitesmoke;
}
#clickMe {
position: relative;
top: 0;
left: 0;
}
var page = document.getElementById("page");
var pageWidth = page.clientWidth;
var pageHeight = page.clientHeight;
var button = document.getElementById("clickMe");
var buttonWidth = button.clientWidth;
var buttonHeight = button.clientHeight;
function moveButton() {
var x = Math.floor(Math.random() * (pageWidth - buttonWidth));
var y = Math.floor(Math.random() * (pageHeight - buttonHeight));
button.style.left = x + "px";
button.style.top = y + "px";
}
document.getElementById("move").onclick = moveButton;

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.

How can I resize and crop/letterbox image to completely fill div with image whatever resize

This is what I need:
The image must completely fill 100% the area the div covers - left to
right and top to bottom.
the image must not be squashed or streched - just be cropped or
must overflow.
The image must be kept as small as possible, so whatever the resize - you
can still see either the very sides OR the very top and bottom.
The div itself will be adjusting in height and width as both are a percentage of the main window.
I have found a little bit of JavaScript here that is manipulating the image just how I want when the window is resized, but is displaying it in the whole window.
<html>
<head>
<title>test</title>
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var height_ratio = image_height / window_height
var width_ratio = image_width / window_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
else
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
}
</script>
</head>
<body onresize="resizeImage()">
<img onload="resizeImage()" src="f/a.jpg">
</body>
</html>
Here is a demo
Please don't just answer that all I need is:
<img style="width : 100%;">
This is so much more than that.
It's not too easy to explain but check the demo and drag the corner of the window around and that'll be worth 1000 words...!
Can it (or something like it) be made to work the same way within a % sized div?
I wrote a jQuery plugin that does exactly this. Check out my blog post here and the demo here
jQuery.fn.resizeToParent = function(options) {
var defaults = {
parent: 'div'
}
var options = jQuery.extend(defaults, options);
return this.each(function() {
var o = options;
var obj = jQuery(this);
// bind to load of image
obj.load(function() {
// dimensions of the parent
var parentWidth = obj.parents(o.parent).width();
var parentHeight = obj.parents(o.parent).height();
// dimensions of the image
var imageWidth = obj.width();
var imageHeight = obj.height();
// step 1 - calculate the percentage difference between image width and container width
var diff = imageWidth / parentWidth;
// step 2 - if height divided by difference is smaller than container height, resize by height. otherwise resize by width
if ((imageHeight / diff) < parentHeight) {
obj.css({'width': 'auto', 'height': parentHeight});
// set image variables to new dimensions
imageWidth = imageWidth / (imageHeight / parentHeight);
imageHeight = parentHeight;
}
else {
obj.css({'height': 'auto', 'width': parentWidth});
// set image variables to new dimensions
imageWidth = parentWidth;
imageHeight = imageHeight / diff;
}
// step 3 - center image in container
var leftOffset = (imageWidth - parentWidth) / -2;
var topOffset = (imageHeight - parentHeight) / -2;
obj.css({'left': leftOffset, 'top': topOffset});
});
// force ie to run the load function if the image is cached
if (this.complete) {
obj.trigger('load');
}
});
}
And if you want the image to resize when the window is resized, just bind a resize handler to the window:
$(window).resize(function() {
$('img').resizeToParent();
});
Ok I've been playing around with it:
<html>
<head>
<title>test</title>
<style>
#imgarea {
position:absolute;
right:0px;
height:75%;
width:70%;
top:25%;
}
</style>
<script type="text/javascript">
function resizeImage()
{
var window_height = document.body.clientHeight
var window_width = document.body.clientWidth
var image_width = document.images[0].width
var image_height = document.images[0].height
var area_width = window_width * 0.7
var area_height = window_height * 0.75
var height_ratio = image_height / area_height
var width_ratio = image_width / area_width
if (height_ratio > width_ratio)
{
document.images[0].style.width = "100%"
document.images[0].style.height = "auto"
}
else
{
document.images[0].style.width = "auto"
document.images[0].style.height = "100%"
}
}
</script>
</head>
<body onresize="resizeImage()">
<div id="imgarea">
<img onload="resizeImage()" src="f/a.jpg">
</div>
</body>
</html>
It keeps resizing as the div resizes - as mentioned the div is
resizing with the window - this one keeps working seemlesly.
It seems to be OK across IE9, Fire Fox, Oprea, Chrome, and safari
over xp and 7
so really it answers my question perfectly, its just - now i've seen Christian's centering version i wish i had the know-how to make this do it i've tried a few things but am now stuck. Any Ideas?
P.S. if you dont know the width and height % of the div when you right the script i think it could be got with GetElementById - somehow... beyond me though;)

Categories

Resources