working out a ratio based on a previously calculated value - javascript

I'm trying to produce a photo slider that is dynamically sized according to the viewport size, but maintains a 4:3 ratio regardless of viewport dimensions.
The page I'm working on is here:
http://steph-morris.com/thenovel_III.html
Width is currently being calculated by grabbing the viewport width and subtracting the size of the menu bars, like so:
$(document).ready(function(){
var height = $(window).height(), width = $(window).width();
$('img').css('width', (width - (281+(height*0.32))) + 'px');
});
(Where one menu is a known width of 281px and the other menu is calculated as height*0.32).
I need to calculate height in relation to width in a 4:3 ratio.
I am brand new to jQuery maths and haven't been able to get a working nested equation that does something like
$('img').css('height', ((width - (281+(height*0.32))*thecorrectratio) + 'px');
Also, this is not an efficient approach- I should be storing the outcome of the 'width' calculation I think and calculating it more as
$('img').css('height', (widthvalue*thecorrectratio) + 'px');
But I also don't know how to do that with jQuery.
So I would really appreciate any assistance with (a) how to write a good nested equation to work out the value of 'height', or (b) how to save the outcome of the 'width' equation so that it can be used again, and obviously (c) the correct way to calculate a 4:3 ratio.

you can write an equation with a function :
$(document).ready(function(){
function height43(width){
return Math.floor(parseInt(width)/4*3);
}
var menuWidth = 281;
var slideWidth = $(window).width()-menuWidth;
var slideHeight = height43(slideWidth);
// all variables and functions declared directly inside some brackets
// are available everywhere inside or subinside these brackets so you can reuse them
function anotherFunctionSample(){
alert('slideHeight : '+slideHeight);
alert('new calculation with another width : '+height43(700));
}
anotherFunctionSample();
});
Then please have a look at javascript basis before trying going elsewhere...and maybe some primary Math lessons about cross product ;)
Then jQuery is 'just' a javascript wrapper that helps a lot through different browser compatibilities interpreting things quite differently...work hard

Related

How to get height in AngularJS like in JQuery?

I have this jquery snippet below:
$(document).ready(function() {
var height = Math.max($("#one").height(), $("#two").height());
$("#one").height(height);
$("#two").height(height);
});
I want to convert that to AngularJS, but I've been having an issue on actually getting the height. I've tried many different things including offsetHeight and scrollHeight and they all return 0. Is that because I'm using a table? I'm not sure how to do it / if I'm doing it right. Here's kind of an outline of what I've been trying to do so far:
$scope.height = function()
{
var height = window.Math.max(HEIGHT OF MY ELEMENT "firstTable", HEIGHT OF MY ELEMENT "secondTable");
//Now get the height and set it.
};
I'm not sure if I should make this into a directive and put it in my table (where I can access $element) or what.
Thanks in advance
What you're looking for isn't to use AngularJS to get height, but rather use native JavaScript.
Use document.getElementById() to select your element then use .offsetHeight to get the height and finally .style.height to set your height.
Your code would look a little like this:
var elementOne = document.getElementById("one"),
elementTwo = document.getElementById("two"),
height = Math.max(elementOne.offsetHeight, elementTwo.offsetHeight);
elementOne.style.height = height;
elementTwo.style.height = height;
Note that I created variables for each element to avoid repeatedly retrieving the element via document.getElementById() for getting and setting the height.
I would recommand using plain old javascript to do so.
Looks like this works well :
document.getElementById('someDiv').clientHeight;
// clientHeight includes the height and vertical padding.
document.getElementById('someDiv').offsetHeight;
// offsetHeight includes the height, vertical padding, and vertical borders.
document.getElementById('someDiv').scrollHeight;
// scrollHeight includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.
Found solution on Stackoverflow : CSS / JavaScript - How do you get the rendered height of an element? so I do not have any merit ;).
jqLite (which is included in Angular) is limited and doesn't offer a function to calculate the height.
Your best options here is to inject the element into controller,
and get the height via:
element[0].offsetHeight;
Demo on plnkr: http://plnkr.co/edit/g45SX4unuCNwlVIUEw4j?p=preview

jquery returning different height everytime I reload

I am trying to create a light box kind of thing in jQuery. For vertically aligning my lightbox,I am using jQuery. Here is my plugin code:
(function($){
$.fn.lightbox = function(){
return this.each(function(){
/*plugin code starts here*/
var self = this;
console.log(self);
/*
* Now we will vertically align the lightbox
* To do that we will calculate the body's height,lightboxes height
* and then subtract later from earlier one.This will give us the total empty space
* So the margin from the top of lightbox will be half of the result we got from subtraction
*/
//calculating body's height
var doc_body_height = $('body').height();
var lightbox_height = $(self).height();
var margin_top = (doc_body_height - lightbox_height)/2;
$(self).css('margin-top',margin_top);
console.log($(self).height());
/*plugin code ends here*/
});
}
})(jQuery);
But the problem is, I am getting either 18 or 300 as height. 300 is the actual height of the div#lightbox,I don't know why the same function is returning different heights randomly.
See Image:
Clearly the div#lightbox is not 18px in height.
You are calculating the height using the $('body').height(). This is the computed value for the height of the body element. That means that for a page with just one visible element that is 50px high on it, the body will return 50px. Conversely, a long page that requires lots of scrolling will return the entire body height, not just the portion that is visible in the viewport.
You need to use $(window).height(); in your calculation instead.
But the problem is, I am getting either 18 or 300 as height. 300 is
the actual height of the div#lightbox,I don't know why the same
function is returning different heights randomly -Rajat Saxena
At original post
var self = this;
console.log(self);
var lightbox_height = $(self).height();
window.innerHeight appear to return viewport of window . See Window.innerHeight .
Try, at console , this page , while periodically adjusting console "height" , and within piece at original post
console.log($(window).height()
, $(self).height()
, $(window)[0].innerHeight
, $(window).height() === $(self).height()
, $(this).height());
If you're only supporting modern browsers then you could use CSS and take advantage of a flexbox http://css-tricks.com/snippets/css/a-guide-to-flexbox/

Link two HTML divs' dimensions to each other?

If I have div A and div B, is there a way to say A.width = b.width = MAX(a.width, b.width) ? That is, whichever has the largest inner content would dictate how large both are.
The actual problem I'm trying to solve is with columns - left, middle, and right. I want the left and right to be the same fixed width (but this could vary depending on their content).
It is not possible to use CSS to achieve this. However, if there is a way to do it with a JS-based solution. Here I am using jQuery. Let's say you have two divs, with classes a and b respectively.
$(function() {
function equalizeSize($ele) {
if($ele.length > 1) {
// Let CSS automatically calculate natural width first
$ele.css({ width: 'auto' });
// And then we fetch the newly calculated widths
var maxWidth = Math.max.apply(Math, $ele.map(function(){ return $(this).outerWidth(); }).get());
$ele.css({ width: maxWidth });
}
}
// Run when DOM is ready
equalizeSize($('.a, .b'));
// Run again when viewport has been resized, which **may** affect your div width.
// This is optional, but good to have
// ps: You might want to look into throttling the resize function
$(window).resize(equalizeSize($('.a, .b')));
});
See proof-of-concept fiddle here: http://jsfiddle.net/teddyrised/N4MMg/
The advantages of this simple function:
Allows you to dictate what elements you want to equalize widths with.
Uses the .map() function to construct an array, which we then use Math.max.apply to get the maximum value in the array
Forces automatic calculation of width when the function first fires (especially when resizing the viewport)
Allows you to call to recalculate the size again, using the handler equalizeSize() when you change the content in the divs... you can call the function again, say, after an AJAX call that appends content to either element.
It is not very clear what you want from the description. but I can rewrite your code this way.
var properWidth = Math.max($("#a").width(), $("#b").width());
$("#a").css("width", properWidth + "px");
$("#b").css("width", properWidth + "px");
I am not sure if it is this kind of solution you want.
I'm not sure there is a way to do it like that. But why not make a default function to set the size:
function changeSize(w, h)
{
A.setAttribute('style', 'width:'+w+'; height:'+h);
b.setAttribute('style', 'width:'+w+'; height:'+h);
}
Working fiddle: http://jsfiddle.net/kychan/ER2zZ/

Javascript function to find total page height

I'm after a simple javascript function that will detect the total height of my web page which is dynamic and apply it to the height of a div which is the page background. Would it be possible to implement it?
The div is called bg...
Any ideas? Thanks in advance
Try:
var height = body.offsetHeight ? body.offsetHeight : html.offsetHeight;
document.getElementById ('divID').style.height = height + 'px';
Here an useful documentation:
http://www.quirksmode.org/dom/w3c_cssom.html
Im using currently following code to do that:
var getBodyHeight = function () {
var d = document,
bd = d.body,
dd = d.documentElement,
max = Math.max(
bd.scrollHeight,
bd.offsetHeight,
bd.clientHeight,
dd.offsetHeight,
dd.scrollHeight,
dd.clientHeight
);
return max;
};
This is what I use to figure out the height of content in iFrame for the purpose of adjusting it properly.
var body = document.body,
html = document.documentElement,
height = 0;
height = body.offsetHeight;
if(height === 0){
height = html.offsetHeight;
}
The reason for checking the body first is that the height of html is actually the height of the iFrame, which could be bigger than the content itself. However, in certain cases such as when body has no height, then it falls back to use height of html instead.
For your case, you might want to experiment with a similar scheme. I'm not sure why you have to use a div to set background so I can't really suggest a better alternative (if any).
Solution based on the comment below:
What you can do is the following. Have a div inside the main container with position absolute, width/height 100% and z-index -1. Then it will always be the correct size no matter how large the contain grow or shrink. With this approach, you will have to make sure that container always has size. This is a pure CSS solution, which might be simpler than using Javascript to adjust.
var height = screen.height;
var width = screen.width;
var resolution = width+"x"+height;
alert(resolution);
it gives the resolution of the screen.i know you want page height and width but it will help you later in web development. i am using it as most important part for my web!

jQuery calculation doesn't add up as expected when toggling height

I have the following function for calculating the height of .node. It then takes away the height of a possible image, .node-image, from the height of the .node, and sets a column, .node-content-column to have a height that is the difference (i.e. 500 - 50 = 450; column becomes 450 in height).
function initColumnSizer() {
imageHeight = $('.node-image').outerHeight(true);
resizeHeight = ($('.node').outerHeight() + 75) - imageHeight;
$('.node-content-column').removeAttr('style');
$('.node-content-column').css('min-height', resizeHeight);
$('.node-content-column').css('height', 'auto !important');
$('.node-content-column').css('height', resizeHeight);
}
This function gets called on page load, and resizes .node-content-column as expected.
It also gets called when a div within .node is toggled using jQuery.toggle(), but this calculation returns a larger number everytime, instead of reverting back to the original once this toggle is reverted.
Can anyone see where I am going wrong with this calculation? Or if I am going about it the wrong way?
Thanks in advance!
Karl
1) Maybe the problem is in outerHeight() function (it takes into account padding and border). Try using just height or clientHeight:
var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
2) why do you need to cleanup the whole elements' style?
and then you try to assign height = auto, and after that: height = resizeHeight - what's the purpose for that ? check the logic of your code.
outerHeight(true) will return height + padding + border + margin. Possibly, you might want to use height() ?
Most possible is that "larger number everytime" have always constant difference -- for example 75.
May be you just have some dependecies between .node-content-column and .node?
If your nodes like .node-content-column, .node and .node-image are all singles, then it's better to use IDs for them -- not CSS classes.

Categories