Jquery progressbar random image width - javascript

I really don't know what im doing wrong. I want to change the width of the image to a random number from 0 - 100%. Can someone tell me what i'm doing wrong?
function progress(){
$("body").append("<div class='main_div'></div>");
var x = Math.floor(Math.random() * 10) + 1;
var x = 5;
for(var i = 0; i < x; i++){
$(".main_div").append("<div class='statusbar'></div>");
$(".statusbar:nth-child(" + x + ")").append("<img src='project_status.gif'>");
var c = Math.floor(Math.random() * 100) + 1;
$(".statusbar:nth-child(" + x + ") img").css({ "width", "(" + c +")%" });
}
}

There are errors in your Math.floor() function: Instead of
Math.floor(Math.random() * 10) + 1;
It should be
Math.floor((Math.random() * 10) + 1));
with the +1 within the Math.floor brackets.
I don't know if it would be helpful or not, but I have previously produced a random-size progress bar here: http://jsfiddle.net/cu22W/10/

The issue is with this statement:
$(".statusbar:nth-child(" + x + ") img").css({ "width", "(" + c +")%" });
You should read up on JQuery .css() function : http://api.jquery.com/css/
But when you use the .css() function with { } brackets the syntax is the same as CSS itself.
So for your statement the proper way would be :
.css({ width : c +"%" })
or, if you wanted to keep it the way you have it just remove the { } brackets :
.css( "width", c +"%")
I am also pretty sure you don't need to wrap c in ()

Related

Adding numbers instead of adding increment

I have a small script that increments the number by the number in a given time period. If incrementing by one value++ works, if I want to add another value of the type generated by the math.random function instead of adding, add to the existing value. How can I change this? I want the generated number to add to an existing value in innerHTML.
document.getElementById("data-gen").innerHTML = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);
nowResources = function() {
document.getElementById("data-gen").innerHTML += Math.floor((Math.random() * 10) + 1);
setTimeout(nowResources, 1000);
}
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
You append numbers to a string. Convert your innerHTML to a number with parseInt and it'll work as you expecting.
document.getElementById("data-gen").innerText = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);
nowResources = function() {
// parseInt( yourString, radix )
const num = parseInt( document.getElementById("data-gen").innerText, 10 );
document.getElementById("data-gen").innerText = num + Math.floor((Math.random() * 10) + 1);
setTimeout(nowResources, 1000);
}
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
But one downside is, that you are querying the DOM each time you want to change it. It's better to store your number outside of your timeout and use an interval like this:
let num = Math.floor((Math.random() * 100000) + 1) + Math.floor((Math.random() * 100) + 1);
document.getElementById("data-gen").innerText = num;
nowResources = function() {
num += Math.floor((Math.random() * 10) + 1);
document.getElementById("data-gen").innerText = num;
}
setInterval( nowResources, 1000 );
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
This way you don't need to parse your number with each iteration.
When you use + it takes as string and concatenate as a string, convert it to an integer using parseInt
document.getElementById("data-gen").innerHTML = parseInt( document.getElementById("data-gen").innerHTML) + (Math.floor((Math.random() * 10) + 1));
DEMO
document.getElementById("data-gen").innerHTML = Math.floor((Math.random() * 100000) + 1)+ Math.floor((Math.random() * 100) + 1);
nowResources = function() {
document.getElementById("data-gen").innerHTML = parseInt( document.getElementById("data-gen").innerHTML) + (Math.floor((Math.random() * 10) + 1));
setTimeout(nowResources, 1000);
}
nowResources();
<span id="data-gen" style="color: #da5cb2;"></span>
To keep the logic clear, just use a local variable to store the value, no need to backward converting via parseInt and weary (and expensive, and messy) DOM element methods dancing:
var value = 0;
function setValue(addValue) {
value += addValue;
document.getElementById("data-gen").innerHTML = value;
}
nowResources = function() {
setValue(Math.floor((Math.random() * 10) + 1))
setTimeout(nowResources, 1000);
}
nowResources();

Change CSS with Javascript but using Variables

I know this:
document.getElemntById('object').style.height='50px';
But instead of '50' (string), I want to use another variable (for Example number).
I wanted to do this because I want random numbers.
Any easy way to do it?
Simple
var foobar = 25;
document.getElementById('object').style.height=foobar + 'px';
This is how you would do it with a random number between 1 and 100. Read more about Random
var RandomNumber = Math.floor((Math.random() * 100) + 1).toString();
document.getElementById('object').style.height=RandomNumber + 'px';
You can use a variable anywhere you can use a string literal.
var foo = "50px";
document.getElementById('object').style.height = foo;
You can generate random number like this and set the height. In the below example maxHeight is exclusive.
var minHeight = 10;
var maxHeight = 20;
var randomHeight = Math.floor((Math.random() * (maxHeight - minHeight)) + minHeight);
document.getElemntById('object').style.height = randomHeight + 'px';
Use Math.random() * 300 to get a random from 1-300 float number, then parseInt to get a integer.
int + string will get you string in JS so no need to convert, just use randompx + 'px'
var randompx = parseInt(Math.random() * 300) + 1;
//document.getElementById('object').style.height=randompx + 'px';
console.log(randompx+'px');
Try this
document.getElemntById('object').style.height= randomNumber + 'px';

How to select elements to apply a transformation(rotation, etc) to?

I am trying to rotate or transform all elements inside a div but I currently have this function. It rotates all elements on the page. How can I select a div or a class to rotate instead?Array.from(document.all).forEach(o => o.style.transform = "rotate(" + Math.floor(Math.random() * 27 - 12) + "deg)")
You need to use document.getElementsByClassName() or document.getElementsByTagName():
var selected = document.getElementsByClassName('myClass');
Array.from(selected).forEach(o => o.style.transform = "rotate(" + Math.floor(Math.random() * 27 - 12) + "deg)")
function randomRotate(selector) {
var elem = document.querySelector(selector);
if (!elem) return;
elem.style.transform = "rotate(" + Math.floor(Math.random() * 27 - 12) + "deg)"
}
randomRotate('.someClass');
Basically it doest the same as your code, but instead of taking all elements it looks for particular via selector. If there are multiple elements with such class it will apply rotation only for first of them.
So if you want to apply rotation to all objects with that class, you should use a bit another function:
function randomRotate(selector) {
var elems = document.querySelectorAll(selector);
if (elems.length === 0) return;
elems.forEach(function(el){
el.style.transform = "rotate(" + Math.floor(Math.random() * 27 - 12) + "deg)"
})
}
randomRotate('.someClass')

understanding safari SVG redraw bug fix.

I was just going through THIS snap sbg demo and i came across the following lines of code:
var flag,
len = Snap.path.getTotalLength(pth.attr("d"));
Snap.animate(0, len, function (l) {
// Safari bug workaround: forcing redraw
g.attr({width: 100 + (flag = !flag ? 1e-5 : 0) + "%"});
//
var dot = pth.getPointAtLength(l);
flight.attr({
d: pth.getSubpath(0, l)
});
pln.attr({
transform: "t" + [dot.x, dot.y] +
"r" + (dot.alpha - 90)
});
gr.attr({
transform: getShift(dot)
});
}, 10000);
Now i am not quite understanding the below line of code:
g.attr({width: 100 + (flag = !flag ? 1e-5 : 0) + "%"});
What exactly is 1e-5 ? can somebody explian ?
flag = (!flag ? 1e-5 : 0) + "%"
is the same as:
if(!flag) {
flag = 0.00001; //1e-5 is the scientific notation for 1^-5
} else {
flag = 0;
}
flag = flag + "%";
I am not familiar with Snap, but it seems like the code is changing the width property every frame from 100% to 100.00001%, causing a redraw. 1e-5, as mentoined in comments is number written using scientific notation for real numbers and is equal to 10^-5 = 0.00001.

How to use "+=" assignment operator with variable inside animate?

I'm struggling here to solve this.
http://jsfiddle.net/yhcqfy44/
The animation is supposed to automaticaly scroll top relative to <span> height each time when the scroll bar appears.
I have write this but with no luck:
var hheight = $('<span>').height();
var i = 0;
var blackposition;
var square = $('<span></span>').first();
var endless = setInterval(function() {
if (i % 4 == 0) {
blackposition = Math.floor(4 * Math.random());
}
var math = (blackposition == (i % 4)) ? 0 : 1;
square.clone().addClass('color_' + math).text((math < 1) ? 'even' + i : 'odd' + i).appendTo('#container');
i++;
$('body,html').animate({
scrollTop: '+=' + hheight + 'px'
}, 1000, 'linear')
}, 500);
$(window).on('scroll', function() {
if ($("span").offset().top + $("span").height() < $(window).scrollTop()) {
$("span").slice(0, 4).remove();
};
});
Is there a solution for doing this ?
You are providing a string for the scrollTop property, and JavaScript is just going to treat that as a string and not an operator, apart from that I don't think you can have an operator there so I would try something like this scrollTop: $(document).height() + 'px' I think that does what you want it to, take a look at this http://jsfiddle.net/yxbj0fen/2/
Basically that just scrolls to the bottom of the document, but you can replace that with another container (e.g. a div)

Categories