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);
}
Related
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;
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/
I would like to set the min-height of a HTML element to the maximum of two values, but unfortunately css doesn't support max().
Here's my css code:
#content{ min-height:calc( 100% - 100px); }
The other value is constant number (400px). I think I have to use JS, but I cant figure out how to do that.
Here is my JS code:
function layout(){
var y = document.getElementById("content");
y.style.minHeight = Math.max(parseInt(y.style.minHeight), 400).toString + "px";
}
window.onload = layout;
window.onresize = layout;
alert(parseInt(y.style.minHeight)) gives me naN.
What am I doing wrong?
Regards
I can't determine a direct way to get the calculated result of the min-height style.
But the following function assigns it to the height of the element, from which we can get it as the element's new offsetHeight.
The function then restores the original height of the element:
function layout() {
var y = document.getElementById('content'),
h = y.offsetHeight;
y.style.height = getComputedStyle(y).getPropertyValue('min-height');
y.style.minHeight = Math.max(y.offsetHeight, 400) + 'px';
y.style.height = h + 'px';
} //layout
Working Fiddle
first of all i want to say that the following function is by chance and by this i mean that its functioning is very strange:
function x (e,s,v){ // e =element, s = desired size of an element, v = speed
var div = document.getElementById(e),
width = 0;
for(var i =0; width<s; i++){
if(i%v === 0){
width = width+1;
div.setAttribute('style', 'width:'+width+'px;');
}else{
width = width +0;
}
};
};
this function is working perfectly and doing what i want but the problem is that the width is changing at once when the working of this function is finished.
in detail
i want that the width of an element increase smoothly, increase 'one' by 'one' px. so i made this function.
there is an if statement because if i didn't put that there then the width of that element would increase at once. that if statement delay the time between the adding of two pixels
but now the problem is that it is adding pixels one by one but the width is increasing at once after the completion of the function.
for example if i write in console x('aynElement', 500, 100) then it is adding pixels one by one but the width of the element is increasing at once when the function stop functioning
you can see this yourself in console
link to JsFiddle for full code
secondly
the problem is that this is strange. you had absolutely felt weird after reading this function. please anyone explain me this weirdness.
thanks
You can use setTimeout() to do this.
function x(e, s, v) { // e =element, s = size of an element, v = speed
var div = document.getElementById(e),
width = 0;
for (var i = 0; i < (s - width); i++) {
setTimeout(function() {
div.setAttribute('style', 'width:' + width+++'px;');
}, i * (1 / (v * 0.01)));
};
};
x('d1', 400, 10)
#d1 {
width: 100px;
height: 100px;
background-color: #aaa;
}
<body>
<div id="d1" style="width:200px;"></div>
</body>
I think this would solve it better (might need the one or other adjustment, just a quick scrape):
DEMO
setInterval(function(){
grow('id',250) //set your parameters here
}, 100); //this is the speed - the lower the quicker
var width = 1;
function grow(e,s) {
document.getElementById('d1').style.width = width+"px";
width++;
};
setInterval(function(){
grow('id',500)
}, 10);
var width = 250;
function grow(e,s) {
document.getElementById('d1').style.width = width+"px";
width++;
};
#d1{
height: 100px;
background-color: #000;
}
<body>
<div id="d1" ></div>
</body>
What I am trying to do is have content always be in the center of a container even if the margin size and content size change. This also means that the container size must change on it's own given the amount of margin and width of the content. Here is a js fiddle that has a general set-up of a function and an alert that gives the output: http://jsfiddle.net/jpY5n/
function resizeContainer(size, distance) {
var postWidth = size;
var postApart = distance * 3;
return postWidth + postApart;
};
$(document).ready(function () {
$('#container').width(resizeContainer($("#content").width(),$("#content").css("margin-left"));
});
I could theoretically use the function I have set up in order to change the width of the posts, but it can't take in the math of the margins because, as you can see in the alert, the margin is 10px, not 10, so the math comes back as NaN...Is there a way to to make the margin settings let us say ßpx to just ß?
You can get the numeric value of the margin by parsing the string into a Number after replacing 'px' with '':
var margin = Number($('#content').css('margin-left').replace('px',''));
Here's the updated Fiddle.
HTML
<div id="container">
<div id="content"></div>
</div>
JavaScript (jQuery)
function resizeContainer(size, distance) {
var postWidth = size * 2;
var postApart = distance * 3;
return postWidth + postApart;
};
$(document).ready(function () {
alert("Container width should be set to " + $("#content").width() + " times 2 plus " + $("#content").css("margin-left") + " times 3");
var width = Number($('#content').width());
var margin = Number($('#content').css('margin-left').replace('px',''));
$('#content').width(resizeContainer(width,margin));
});