How to use maximum for JS math in CSS-related function - javascript

I've written a function below that allows the user to control the size of certain objects based on a scroll position. The issue is that I don't know how to force the math to stop a minimum or maximum.
In this case, I would like the header width to decrease until it's 25% wide.
function EasyPeasyParallax() {
var scrollPos = $(document).scrollTop();
var currentSize = 100
$('.header').css({ 'width': (currentSize - Math.min(scrollPos/1.5,2000)) + '%' });
};
$(document).ready(function() {
$('body').bind('mousewheel', EasyPeasyParallax);
});
I've tried Math.max(), but ultimately don't really know how to make this happen.
Any help?
Codepen here: http://codepen.io/bsley/pen/gGyhm

I might be barking up wrong tree, but you could set min-width and max-width like this, because you are using .css() not .width():
.header{
min-width:25%;
max-width:100%;
}
Hope this helps.

Try this:
var width = (currentSize - Math.min(scrollPos/1.5,2000)),
min = 25, // Min percentage
max = 100; // Max percentage
width = (width < min) ? min: (width > max) ? max : width;
$('.header').css({ 'width': width + '%' });
I'm using a ternary operator as a shorthand, it basically does this:
if(width < min) {
width = min;
} else {
if(width > max) {
width = max;
} else {
width = width;
}
}

Related

Keeping aspect ratio when height AND width both need to change

I am trying to make an image resize based on values given to it (width/height)
The values must not exceed the maxheight and maxwidth but must maintain ratio.
Right now it works if I make the height or width too big, but if both are triggered it doesn't work. So it's a logical error, can someone please help me with this.
if (maxwidth <= width || maxheight <= height) {
if(width > maxwidth) {
var newheight = height * (maxwidth/width);
newwidth = maxwidth;
console.log("new height");
}
if(height > maxheight) {
var newwidth = width * (maxheight/height);
newheight = maxheight;
console.log("new width");
}
For it in action go here: https://codepen.io/anon/pen/XBEvNO
The error occurs when say width is 1500 and height is 600.
I know it's because the second if statement overwrites the first, but I don't know how to fix this logic.
First off, if you do not want the values to exceed their maximums, but do want to scale the image so that it keeps the ratio, you need to set the size values to the maximum before you work out the resulting width/height from that change in width/height.
Second, if you want the ratio to be the same, then you should not be able to change both the height and the width at the same time, because if you change the width, there is exactly one other height value that maintains the ratio
The math for this would be like so:
R = Ratio (Assuming your max values are the ratio you want R = MaxWidth / MaxHeight)
H = Height
W = Width
W = H*R
H = W/R
if (maxwidth <= width) {
if(width > maxwidth) {
newwidth = maxwidth;
var newheight = newwidth / (maxwidth/maxheight);
console.log("new height");
}
Not only would this need to be changed so that the ratio is a proper ratio but the code you have for making it smaller would also need to be altered.
If by ratio you did not mean the ratio of the original images W/H, please clarify.
For maintaining the inputed user ratio try this:
if (maxwidth <= width || maxheight <= height) {
var ratio = width/height;
var heightRatio = height/maxheight;
var widthRatio = width/maxwidth
if(width > maxwidth && widthRatio >= heightRatio) {
newwidth = maxwidth;
var newheight = newwidth / ratio;
console.log("new height");
}
else if(height > maxheight && heightRatio > widthRatio) {
newheight = maxheight;
var newwidth = newheight * ratio;
console.log("new width");
}
Checking the larger of the sizes compared to their max size ensures that when the scaling happens, the size largest over the maximum size gets scaled to max, this way the other size does not still go over max at some times
You need to decide whether you will scale by the ratio of height/maxHeight or width/maxWidth then see which one you can use without making the other dimension too big. Another way of thinking is asking: if we maximize the width, does the height get too big? If not maximize the width, otherwise maximize the height. Either way, we scale by the same scale for width and height so the aspect ratio stays the same. (You would probably want to add sanity checks for divide by zero)
function resize(size, max){
// can we maximize the width without exceeding height limit?
let resize_factor = (size.height / ( size.width/max.width)) <= max.height
? size.width/max.width
: size.height/max.height
return {width: size.width/resize_factor, height: size.height/resize_factor}
}
let max = {
width: 100,
height: 50
}
console.log(resize({width: 500, height:50}, max))
console.log(resize({width: 500, height:1000}, max))
console.log(resize({width: 40, height:10}, max))
console.log(resize({width: 1, height:2}, max))
console.log(resize({width: 2, height:1}, max))

Increase element size everytime window is resized

my problem today is that I have 12 elements with size 60px x 60px and I'd like to increase the size with 0.2 everytime the screen size increase of 10px, with javascript. For example: screensize 600px and element size 60.2 x 60.2, screensize 610px and element size 60.4 x 60.4 and so on. It would give something like this to increase :
var circle_data={
container: document.querySelector(".container"),
classname: "astro-item",
nb_elem: 12,
elem_size: 60,
};
var screenSize = window.innerWidth;
circle_data.elem_size += 0.2;
The thing is that I don't know how to increase everytime the screen size increase by 10px
Thanks for your help !!
So with your answers here's the code I tried but it doesn't work, maybe because I already have a function that set elements size up, here's the full script:
function circle_container(objdata) {
var circle_dim=objdata.container.getBoundingClientRect();
var rayon=Math.round(circle_dim.width/2 - objdata.elem_size/2);
var center_x=rayon;
var center_y=rayon;
if (objdata.rayon) rayon*=objdata.rayon/100;
for(var i=0;i<objdata.nb_elem;i++) {
var new_elem=objdata.container.querySelector("."+objdata.classname+i);
if (!new_elem) {
var new_elem=document.createElement("button");
new_elem.className="astro-item"+" "+objdata.classname+i;
var new_img=document.createElement("img");
new_img.src = astroList[i].icon;
}
new_elem.style.position="absolute";
new_elem.style.width=objdata.elem_size+"px";
new_elem.style.height=objdata.elem_size+"px";
new_elem.style.top=Math.round( (center_y - rayon * Math.cos(i*(2*Math.PI)/objdata.nb_elem)))+"px";
new_elem.style.left=Math.round( (center_x + rayon * Math.sin(i*(2*Math.PI)/objdata.nb_elem)))+"px";
objdata.container.appendChild(new_elem);
new_elem.appendChild(new_img);
}
}
var circle_data={
container: document.querySelector(".container"),
classname: "astro-item",
nb_elem: 12,
elem_size: 60,
};
function onResize(e) {
var screenSize = e.target.outerWidth;
var width = (screenSize - (screenSize % 100) + (((screenSize + 10) % 100)/10 *2))/10;
var items = document.querySelectorAll('.astro-item');
for(var i = 0; i < items.length; i++) {
items[i].innerHTML = 'width: ' + screenSize + ' size: ' + width ;
}
}
circle_container(circle_data);
addEvent(window,"resize",function() {
circle_container(circle_data);
onresize();
});
The purpose of this function is to create 12 buttons aligned in circle (just like a wheel) and fully responsive, that's why I need them to get bigger when the screen gets larger. Thank you so much !
With pure javascript bind an event onresize and set size based on window width. The size increase 0.2 everytime the screen size increase of 10px:
window.addEventListener("resize", onresize);
var onresize = function(e) {
var width = e.target.outerWidth;
circle_data.elem_size = (width - (width % 100) + (((width + 10) %
100)/10 *2))/10;
}
Working example:
(open in full screen)
*Edited for max min limitations
var min = 500; //min width in pixel
var max= 700; //max width in pixel
window.addEventListener("resize", onresize);
var onresize = function(e) {
var width = e.target.outerWidth;
var s = (width - (width % 100) + (((width + 10) % 100)/10 *2))/10
if(width <=max && width >=min){
//change size here
document.getElementById('s').innerHTML = 'width: ' + width + ' size: ' + s ;
}
}
<span id='s'> </span>

Find max scrolling an element has

I am implementing my own horizontal scrolling with controls (left/right)
How can I find how much scrolling I got to the right?
My code is as follows:
$scope.scrollFilters = function(dir) {
var leftPos = $('.filters').scrollLeft();
var containerWidth = $('.filters').width();
var scrollTo = 0;
if (dir == 'right') {
scrollTo = leftPos + scrolled >= containerWidth ? containerWidth : leftPos + scrolled;
} else {
scrollTo = leftPos - scrolled <= 0 ? 0 : leftPos - scrolled;
}
$('.filters').animate({
scrollLeft: scrollTo
});
};
What I'm interested in is getting the actual $('.filters').width(). At the moment it would just return the width I set up in the CSS, I want to get the actual width if I wouldn't limit the div in width.
P.S. its an AngularJS application, but don't think it does me any good this time.
Thanks for the help!
you should try and grab its max width
var theWidth = Math.max.apply(null, $(".filters").map(function() {
return $(this).outerWidth(true);
}).get());
If there is scroll, it means that an inner element is bigger than an outer element, so you should calculate the difference between the inner width (bigger) and the outer width (smaller) or their heights.
This may help you as you have to apply the same concept: How to get maximum document scrolltop value

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

jQuery - How to know if window is resizing in width/height or both?

I have a little problem with window resizing using jQuery's function .resize(). I would like to know which dimension is getting bigger/smaller - width or height. I need this because if I just put two conditions - if width is for 50px bigger than div and if height is for 50px bigger than div,
// (pseudocode)
if width = div.width + 50px
width = something
if height = div.height + 50px
height = something
then is working on just one condition and I can resize only width or height.
How could I know which dimension is changing in size or if both are?
By saving last window size values in variables.
var h = $(window).height(), w = $(window).width();
$(window).resize(function(){
var nh = $(window).height(), nw = $(window).width();
// compare the corresponding variables.
h = nh; w = nw; // update h and w;
});
Save the previous size and compare with it, everytime the size changes.
For ex:
var prevW = -1, prevH = -1;
$(document).ready(function() {
// ... other stuff you might have inside .ready()
prevW = $(window).width();
prevH = $(window).height();
});
$(window).resize(function() {
var widthChanged = false, heightChanged = false;
if($(window).width() != prevW) {
widthChanged = true;
}
if($(window).height() != prevH) {
heightChanged = true;
}
// your stuff
prevW = $(window).width();
prevH = $(window).height();
});
Demo: http://jsfiddle.net/44aNW/

Categories

Resources