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>
Related
Some context:
I'm working on a Chrome Extension where the user can launch it via default "popup.html", or if the user so desires this Extension can be detached from the top right corner and be used on a popup window via window.open
This question will also apply for situations where users create a Shortcut for the extension on Chrome via:
"..." > "More tools" > "Create Shortcut"
Problem:
So what I need is for those cases where users use the extension detached via window.open or through a shortcut, when navigating through different options, for the Height of the window to be resized smoothly.
I somewhat achieve this but the animation is clunky and also the final height is not always the same. Sometimes I need to click twice on the button to resize too because 1 click won't be enough. Another issue is there is also some twitching of the bottom text near the edge of the window when navigating.
Here's what I got so far:
(strWdif and strHdif are used to compensate for some issues with CSS setting proper sizes which I haven't figured out yet.)
const popup = window;
function resizeWindow(popup) {
setTimeout(function () {
var strW = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("width");
var strW2 = strW.slice(0, -2);
var strWdif = 32;
var bodyTargetWidth = (parseFloat(strW2) + parseFloat(strWdif));
var strH = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("height");
var strH2 = strH.slice(0, -2);
var strHdif = 54;
var bodyTargetHeight = (parseFloat(parseInt(strH2)) + parseFloat(strHdif));
var height = window.innerHeight;
console.log("Window Height: ", height, "CSS Height: ", bodyTargetHeight);
var timer = setInterval(function () {
if (height < bodyTargetHeight) {
popup.resizeTo(bodyTargetWidth, height += 5);
if (height >= bodyTargetHeight) {
clearInterval(timer);
}
} else if (height > bodyTargetHeight) {
popup.resizeTo(bodyTargetWidth, height -= 5);
if (height <= bodyTargetHeight) {
clearInterval(timer);
}
} else {
clearInterval(timer);
}
}, 0);
}, 0400);
}
Question:
Is there a way to make this more responsive, and smooth and eliminate all the twitching and clunkiness?
I guess the issue might be that I am increasing/diminishing by 5 pixels at a time but that is the speed I need. Maybe there is another way to increase/decrease by 1px at a faster rate? Could this be the cause of the twitching and clunkiness?
Also, I should add that troubleshooting this is difficult because the browser keeps crashing so there is also a performance issue sometimes when trying different things.
EDIT:
Another option using resizeBy:
function animateClose(time) {
setTimeout(function () {
var strW = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("width");
var strW2 = strW.slice(0, -2);
var strWdif = 32;
var bodyTargetWidth = (parseFloat(strW2) + parseFloat(strWdif));
var strH = getComputedStyle(window.document.querySelector(".body_zero")).getPropertyValue("height");
var strH2 = strH.slice(0, -2);
var strHdif = 54;
var bodyTargetHeight = (parseFloat(parseInt(strH2)) + parseFloat(strHdif));
var w = window.innerWidth; //Get window width
var h = window.innerHeight; //Get window height
var loops = time * 0.1; //Get nb of loops
var widthPercentageMinus = (w / loops) * -0;
var heightPercentageMinus = (h / loops) * -1;
var widthPercentagePlus = (w / loops) * +0;
var heightPercentagePlus = (h / loops) * +1;
console.log("Window Height: ", h, "CSS Height: ", bodyTargetHeight);
var loopInterval = setInterval(function () {
if (h > bodyTargetHeight) {
window.resizeBy(widthPercentageMinus, heightDecrheightPercentageMinuseasePercentageMinus);
} else if (h < bodyTargetHeight) {
window.resizeBy(widthPercentagePlus, heightPercentagePlus);
} else {
clearInterval(loopInterval);
}
}, 1);
}, 0400);
}
This one is a bit more smooth but I can't make it stop at the desired Height. It also is not differentiating between resizing up or down, also crashes the browser sometimes.
maybe with requestAnimationFrame
try something like this (not tested):
function resizeWindow(popup) {
var gcs = getComputedStyle(window.document.querySelector(".body_zero"));
var strW = gcs.getPropertyValue("width");
var strW2 = strW.slice(0, -2);
var strWdif = 32;
var bodyTargetWidth = (parseFloat(strW2) + parseFloat(strWdif));
var strH = gcs.getPropertyValue("height");
var strH2 = strH.slice(0, -2);
var strHdif = 54;
var bodyTargetHeight = (parseFloat(parseInt(strH2)) + parseFloat(strHdif));
var height = window.innerHeight;
console.log("Window Height: ", height, "CSS Height: ", bodyTargetHeight);
window.myRequestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame;
var hStep = 2; //choose the step. Must be an integer
function internalFunc() {
if (Math.abs(height - bodyTargetHeight) > hStep) {
if (height < bodyTargetHeight)
hStep *= 1;
else if (height > bodyTargetHeight)
hStep *= -1;
popup.resizeBy(0, hStep);
height += hStep;
window.myRequestAnimationFrame(internalFunc)
} else
popup.resizeBy(0, bodyTargetHeight - height)
}
popup.resizeTo(bodyTargetWidth, height);
window.myRequestAnimationFrame(internalFunc)
}
<html>
<head>
<script>
const bodyTargetWidth = 150;
const bodyTargetHeight = 250; //target height
var height; //height at beginning
window.myRequestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame;
var hStep = 5; //choose the step. Must be an integer
var dir;
var myPopup;
function doResize() {
function internalFunc() {
console.log('height: ', height) ;
if (Math.abs(height - bodyTargetHeight) > hStep) {
dir = Math.sign(bodyTargetHeight - height);
myPopup.resizeBy(0, dir * hStep);
height += dir * hStep;
window.myRequestAnimationFrame(internalFunc)
} else
myPopup.resizeBy(0, bodyTargetHeight - height)
}
if (!myPopup || myPopup?.closed) {
myPopup = window.open("about:blank", "hello", "left=200,top=200,menubar=no,status=no,location=no,toolbar=no");
height = 150;
myPopup.resizeTo(bodyTargetWidth, height);
} else {
myPopup.focus();
height = myPopup.outerHeight
}
myPopup.resizeTo(bodyTargetWidth, height);
window.myRequestAnimationFrame(internalFunc)
}
document.addEventListener('DOMContentLoaded', _ => document.getElementById('myBtn').addEventListener('click', doResize))
</script>
</head>
<body>
<button type="button" id="myBtn">Create popup<br>\<br>Reset popup height</button><br>
<p>First create the popup, then change popup height and click the button above again</p>
</body>
</html>
I'm trying to make the font size be responsive and auto adjust the font size depends on width & height of the container(image).
But problem now is when I make the screen size smaller, It keep run the font size "1em" only. It start from // font size in the script, Thank you! :)
can I know where is the problem?
$(function() {
// document
'use strict';
var t1 = $('div.cp');
// Settings
t1.each(function() {
var _t1 = $(this);
// Different Data type
if (_t1.data('type') == "c1")
{
_t1.addClass('red').css(
{
"background-image" : "url('https://www.planwallpaper.com/static/images/violet-vector-leaves-circles-backgrounds-for-powerpoint_PdfkI4q.jpg')",
"background-size" : "100% 100%"
}
);
_t1.append(
'<div class="title">' + 'im red' + '</div>'
);
$(_t1.children()).wrapAll("<div class='ty-container'/>");
} else {
return false;
}
});
// alignment to middle
$('.cp').on('resize',function() {
$(".ty-container").css('margin-top', function() {
return($('.cp').height() - $(this).height()) / 2
});
}).resize();
// font size
textfit();
$(window).on('resize', textfit);
function textfit() {
var w1 = $('.cp').width()-10;
var w2 = $('.title').width();
var wRatio = Math.round(w1 / w2 * 10) / 10;
var h1 = $('.cp').height()-10;
var h2 = $('.title').height();
var hRatio = Math.round(h1 / h2 * 10) / 10;
var final = Math.min(wRatio, hRatio);
$('.cp').css('font-size', final + 'em');
}
});//end
.cp{width:340px;height:156px;display:table;text-align: center;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cp" data-type="c1"></div>
Use font size vw that means viewport width. Must declare viewport width meta at header. and use font-size in css. example font-size: 50vw;
What I am trying to do
I want to display multiple images in the same div of fixed size like the image. There will be multiple divs in the same page. The total size of the divs should not exceed the size of the screen.
function setupView(div, items, height, percentage) {
//get the height for the div
//var max_height = getPossibleHeight(div, items);
if(percentage){
$(div).css("height" , $(window).height() / 100 * height);
} else
$(div).css("height" , height+"px");
$(div).css("line-height",0);
//get the computed height and width
const div_height = $(div).height();
const div_width = $(div).width();
//Calculate the side of each image
const im_side = parseInt(getItemSize(div_width, div_height, items));
var count;
var dv = $(div);
for(count=0; count <= items; count++){
dv.append("<img style='height: "+ im_side +"px;"+" width: "+ im_side+"px" +"' src='../images/done.png'/>");
}
}
function getItemSize(x, y, n) {
var px = Math.ceil(Math.sqrt(n*x/y));
var sx,sy;
if(Math.floor((px*y)/x)*px < n){
sx = y/Math.ceil(px*y/x);
} else{
sx = x/px;
}
var py = Math.ceil(Math.sqrt((n*y)/x));
if(Math.floor((py*x)/y)*py<n){
sy = x/Math.ceil((x*py)/y);
}
else {
sy = y/py;
}
// alert("X="+sx + " Y="+sy);
// if(x>y)
return (sx>sy) ? sx : sy;
}
$(function() {
setupView(".panel-4",25000,"60",true);
// setupView(".panel-5",9000);
alert("Load complete!");
});
This is what is happening right now:
Current Situation
I have used the code provided on
C Code
I want to resize the images in such a way that they fill the div completely without leaving any space.
I am trying to add to the width of the element everytime the setInterval function is invoked
function setProgress(){
var bar = document.getElementById('progress-bar');
var width = 20;
bar.style.width += width + 'px';
//console.log(bar.style.width);
}
window.onload = function(){
setInterval(setProgress, 10);
}
I tried using parseInt(), but everytime I console.log() to the window i see the same width. My end goal is for the width to increase by 20
You need to remove px part from width style and then cast string to number before incrementing it:
function setProgress(){
var bar = document.getElementById('progress-bar');
var width = 20;
bar.style.width = Number(bar.style.width.replace('px', '')) + width + 'px';
//console.log(bar.style.width);
}
Make width a global var, like shown below:
var width = 0;
function setProgress(){
var bar = document.getElementById('progress-bar');
width+= 20;
bar.style.width += width + 'px';
//console.log(bar.style.width);
}
window.onload = function(){setInterval(setProgress, 10);}
Also, you should specify the max width to prevent the progress bar moving outside the working area (for example, modifying the increment line: if(width<500) {width+= 20;} else {return;}).
Alternatively, you can use your original solution by adding couple more statements, namely: removing the "px" unit from style property bar.style.width, then parsing it (converting to Number), then incrementing it and then adding "px" (otherwise, "+" operator will cause a concatenation of strings with output like: 20px20px, 20px20px20px, etc). Such alternative solution will slow down the process and put additional load on CPU (thus, it's not recommended).
Hope this may help. Best regards,
The problem is that width returns a string with units.
Instead, consider storing the number of pixels in a variable:
var bar = document.getElementById('progress-bar'),
width = parseFloat(getComputedStyle(bar).width);
setInterval(function() {
width += 20;
bar.style.width = width + 'px';
}, 10);
var bar = document.getElementById('progress-bar'),
width = parseFloat(getComputedStyle(bar).width);
setInterval(function() {
width += 20;
bar.style.width = width + 'px';
}, 200);
#progress-bar {
background: #0f0;
display: inline-block;
}
<div id='progress-bar'>Progress bar</div>
var width = 0;
function setProgress(){
var bar = document.getElementById('bar');
width+= 20;
bar.style.width = width + 'px';
console.log(bar.style.width);
if(width==200){
width=0;
}
}
window.onload = function(){
setInterval(setProgress, 1000);
}
I'm trying to make a square appear at random positions of the screen. I have set it's position property to be absolute and in javascript i'm running a random number between 0 to 100, this will then be assigned as a percentage to top and left property. however if the random number was ~100 or a bit less the square will appear out of the screen. How do I fix this problem?
var shape1 = document.getElementById("shape1");
//creating random number to 100
function randomNum() {
var r = Math.random();
var y = (r * (100 - 0 + 1)) + 0;
var x = Math.floor(y);
console.log(x);
return x;
}
//reappear at random position
function reappear(object) {
object.style.left = randomNum().toString() + "%";
object.style.top = randomNum().toString() + "%";
object.style.display = "block";
}
reappear(shape1);
code: https://jsfiddle.net/y3m4ygow/1/
You can call the getBoundingClientRect method (MDN reference) on the object and check to see if its bottom property is bigger than window.innerHeight (means it's falling outside the window height), or if its right property is bigger than window.innerWidth (means it's falling outside the window width), and if so, call the reappear function again:
function reappear(object) {
object.style.left = randomNum().toString() + "%";
object.style.top = randomNum().toString() + "%";
object.style.display = "block";
var rect = object.getBoundingClientRect();
if(rect.right > window.innerWidth || rect.bottom > window.innerHeight)
reappear(object);
}
Fiddle update: https://jsfiddle.net/y3m4ygow/2/
As you can see what's happening here is sometimes the object falling out of the document because (the width or height of it + the randomized percentage) is more than document width or height.
For example, say that document width is 1000px and the random number turned out to be 90% (=900px), since the box width is 200px, so you will have 100px out of the screen.
Now you have two solutions:
First: As #Sidd noted, you can check whether the box is in or out using getBoundingClientRect this will return a variable for you having two properties one is bottom which is the distance of the box from the upper edge of the document, the other property is height which is the distance of the box from the left border of the screen.
Now what you can do is compare those two values with the document width and height.
Now by adding those three lines you'll have your problem solved:
var rect = object.getBoundingClientRect(); // getting the properties
if(rect.right > window.innerWidth // comparing width
|| rect.bottom > window.innerHeight) // comparing height
{reappear(object);} // re-randomizing
https://jsfiddle.net/y3m4ygow/2/
this WILL work, but it might produce some flickering with some browsers, and i'm not very comfortable about calling a function inside itself.
Second Solution is: which is what I would prefer you to do, is by not using a percentage, but using a fixed height and width values.
you can get the current height and weight values from the window object and substract your box dimensions from it:
var cHeight = window.innerHeight - 200;
var cWidth = window.innerWidth - 200;
set those two as the maximum value for the top and the right.
function topRandomNum() {
var r = Math.random();
var y = (r * (cHeight - 0 + 1)) + 0;
var x = Math.floor(y);
return x;
}
function rightRandomNum() {
var r = Math.random();
var y = (r * (cWidth - 0 + 1)) + 0;
var x = Math.floor(y);
return x;
}
and here's the fiddle for the second solution: https://jsfiddle.net/uL24u0e4/